微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

实例成员'userEmail'在初始化器中无法访问

如何解决实例成员'userEmail'在初始化器中无法访问

以上错误消息正在我的代码显示。请看下面:

class BottomNaviBar extends StatefulWidget {
  static const String id = 'bottom_navi_bar';

  @override
  _BottomNaviBarState createState() => _BottomNaviBarState();
}

class _BottomNaviBarState extends State<BottomNaviBar> {
  int selectedindex = 0;
  bool showRecipeNotificationBadge = false;
  bool showProfileNotificationBadge = false;
  final _auth = FirebaseAuth.instance;
  FirebaseUser loggedInUser;
  String userEmail;

  @override
  void initState() {
    super.initState();
    getCurrentUser();
  }

  void getCurrentUser() async {
    try {
      final user = await _auth.currentUser();
      if (user != null) {
        loggedInUser = user;
          userEmail = user.email;
      }
    } catch (e) {
      print(e);
    }
  }


  List<Widget> _widgetoptions = <Widget>[
    RecipeBlog(),FavouritesScreen(userEmail: userEmail,),//this is what is causing the error
    ProperHomeScreen(),ProfileScreen(),];

  ...

这很奇怪,因为如果我将实际用户的电子邮件地址作为硬编码字符串传递到FavouritesScreen()中,则代码可以正常工作。但这不能正常工作。

有什么想法吗?

于20/10/20更新:

有关更多上下文,这是build代码

  @override
  Widget build(BuildContext context) {

    List<Widget> _widgetoptions() {
      return [
        RecipeBlog(),ProperHomeScreen(),];
    }

    return Scaffold(
      body: Center(
        child: _widgetoptions.elementAt(selectedindex),bottomNavigationBar: Theme(
        data: Theme.of(context).copyWith(
          // sets the background color of the `BottomNavigationBar`
          canvasColor: Color(0xFF150A42),// sets the active color of the `BottomNavigationBar` if `Brightness` is light
        ),child: BottomNavigationBar(
          items: <BottomNavigationBarItem>[
            BottomNavigationBarItem(
              icon: Icon(Icons.search),title: Container(),BottomNavigationBarItem(
              icon: Icon(Icons.favorite,color: Colors.redAccent,BottomNavigationBarItem(
              icon: Stack(children: <Widget>[
                Icon(Icons.forum),showRecipeNotificationBadge != false
                    ? Positioned(
                  top: 0.0,right: 0.0,child: Icon(Icons.brightness_1,size: 12.0,color: Color(0x00000000)),)
                    : Positioned(
                  top: 0.0,color: Colors.redAccent),]),BottomNavigationBarItem(
              icon: Stack(children: <Widget>[
                Icon(Icons.person),showProfileNotificationBadge != false
                    ? Positioned(
                  top: 0.0,],currentIndex: selectedindex,selectedItemColor: Color(0xFF150A42),backgroundColor: Colors.white,unselectedItemColor: Colors.black38,onTap: _onItemTapped,type: BottomNavigationBarType.fixed,floatingActionButton: selectedindex == 0 ? null : FloatingActionButton(
        backgroundColor: Color(0xff02aab0),onpressed: () {Navigator.push(
          context,MaterialPageRoute(builder: (context) => BottomNaviBar()),);},child: Icon(Icons.search),);
  }
}

解决方法

该错误指出您不能在初始化程序中使用实例成员。这意味着您不能使用另一个实例变量来初始化实例变量。

一个简单的例子:

class Test {
  String initial = "this thing";
  String other = initial;//This leads to the same error that you have
}

这是因为初始化程序在构造函数之前执行。这意味着在初始化时无法访问this,而在访问实例成员时会隐式调用。在对值进行硬编码时,this不再需要初始化变量,因此它可以工作。

在前面的示例中,调用initial实际上是在进行this.initial,但是this不可用,因此将不起作用。

一种解决方法是将_widgetOptions的初始化更改为initState


但是,首先建议不要尝试执行问题中显示的内容。除可能非常特殊的情况外,Widget不应存储在变量中。这是因为,当您更新要传递给窗口小部件的参数时,窗口小部件对象本身将不会更新,因此在重建时不会看到任何可视更改。

请改为使_widgetOptions为您在build中调用的函数,该函数返回List中的Widget个,以便每次创建新Widget对象时,函数称为:

List<Widget> _widgetOptions() {
  return [
    RecipeBlog(),FavouritesScreen(userEmail: userEmail,),ProperHomeScreen(),ProfileScreen(),];
}

此方法还从根本上消除了您收到的当前错误,无需进行任何额外的工作,因为在构造函数创建this之前无法调用该方法。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?