小编典典

错误:只能在初始化程序中访问静态成员,这是什么意思?

flutter

我有这样的东西。我很难理解此错误。为什么在filterController此处访问会出现此错误?但是如果我TextFormField在build方法中移动当前整个创建过程(在注释A和B之间),它不会给出此错误?那么如何将整个TextFormField内部构建方法移动到filterController静态并解决此问题?

class AppHomeState extends State<AppHome> with SingleTickerProviderStateMixin
{

    TabController _tabController;
    final filterController = new TextEditingController(text: "Search");
        //----A
        TextFormField email = new TextFormField(
        keyboardType: TextInputType.emailAddress,
        controller: filterController,    ------>ERROR : Error: Only static members can be accessed in initializers
        );
       //----B

  @override
    Widget build(BuildContext context)
    {
        return new Scaffold(
                appBar: new AppBar(..),
        );
    }
}

我该如何解决这个问题?


阅读 339

收藏
2020-08-13

共1个答案

小编典典

class AppHomeState extends State<AppHome> with SingleTickerProviderStateMixin {

    TabController _tabController;
    final filterController = new TextEditingController(text: "Search");
    TextFormField email = ...

...是一个初始值设定项,目前无法访问this。初始化程序在构造函数之前执行,但是this只允许在对超级构造函数的调用(在您的示例中是隐含的)完成后才能访问。因此,仅在构造函数主体(或更高版本)this中允许访问。

这就是为什么您收到错误消息的原因:

controller: filterController,

访问this.filterControllerthis如果不显式地写,则是隐式的)。

要解决您的问题(假设email需要是final),可以使用工厂构造函数和构造函数初始化列表:

class AppHomeState extends State<AppHome> with SingleTickerProviderStateMixin {
  factory SingleTickerProviderStateMixin() => 
      new SingleTickerProviderStateMixin._(new TextEditingController(text: "Search"));

  SingleTickerProviderStateMixin._(TextEditingController textEditingController) : 
      this.filterController = textEditingController,   
      this.email = new TextFormField(
        keyboardType: TextInputType.emailAddress,
        controller: textEditingController);

  TabController _tabController;
  final filterController;
  final TextFormField email;

或者,当email字段不需要为final时,email可以在构造函数初始化器列表中进行初始化:

class AppHomeState extends State<AppHome> with SingleTickerProviderStateMixin {

  SingleTickerProviderStateMixin() {
    email = new TextFormField(
        keyboardType: TextInputType.emailAddress,
        controller: filterController,
    );
  }

  TabController _tabController;
  final filterController = new TextEditingController(text: "Search");
  TextFormField email;

但是在Flutter中,小部件initState通常用于

class AppHomeState extends State<AppHome> with SingleTickerProviderStateMixin {

  @override
  void initState() {
    super.initState();
    email = new TextFormField(
        keyboardType: TextInputType.emailAddress,
        controller: filterController,
    );
  }

  TabController _tabController;
  final filterController = new TextEditingController(text: "Search");
  TextFormField email;
2020-08-13