为什么在这里访问filterController会出现此错误?但是如果我在构建方法中移动当前的整个TextFormFIEld创建(在注释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(..),); }}
我该如何解决这个问题?
解决方法class AppHomeState extends State<AppHome> with SingleTickerProvIDerStateMixin { TabController _tabController; final filterController = new TextEditingController(text: "Search"); TextFormFIEld email = ...
…是一个初始化程序,此时无法访问它.
初始化器在构造函数之前执行,但只有在完成对超级构造函数(在您的示例中隐式)的调用之后才允许访问它.
因此,只有在构造函数体(或更高版本)中才允许访问它.
这就是您收到错误消息的原因:
controller: filterController,
访问this.filterController(如果你不明确地写它,这是隐式的).
要解决您的问题(假设电子邮件需要最终),您可以使用工厂构造函数和构造函数初始化列表:
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;
或者当电子邮件字段不需要是最终电子邮件时,可以在构造函数初始化列表中初始化:
class AppHomeState extends State<AppHome> with SingleTickerProvIDerStateMixin { SingleTickerProvIDerStateMixin() { email = new TextFormFIEld( keyboardType: TextinputType.emailAddress,); } 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,); } TabController _tabController; final filterController = new TextEditingController(text: "Search"); TextFormFIEld email;总结
以上是内存溢出为你收集整理的dart – 错误:在初始化程序中只能访问静态成员,这是什么意思?全部内容,希望文章能够帮你解决dart – 错误:在初始化程序中只能访问静态成员,这是什么意思?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)