【问题标题】:The instance member 'userInfo' can't be accessed in an initializer [duplicate]无法在初始化程序中访问实例成员“userInfo”[重复]
【发布时间】:2022-03-05 20:34:11
【问题描述】:

我想将 Paricipant 类的实例传递给标签栏。我试图让List迟到,但它没有显示开头的信息(我必须转到另一个页面并返回查看)。

class MainTabBar extends StatelessWidget {
  MainTabBar({Key? key, required this.userInfo}) : super(key: key);

  final ParticipantInfo userInfo;

  final List<ItemView> items = <ItemView>[
    ItemView(title: "User", icon: Icons.account_box, view: UserProfileTab(userInfo: userInfo)),
    ItemView(title: "Current State", icon: Icons.content_paste, view: CurrentStatesTab(roomNumber: userInfo.location,)),
    const ItemView(title: "All data", icon: Icons.table_rows_rounded, view: AllInfoTab()),

  ];

  @override
  Widget build(BuildContext context) {......
lib/main.dart:44:85: Error: Can't access 'this' in a field initializer to read 'userInfo'.
    ItemView(title: "User", icon: Icons.account_box, view: UserProfileTab(userInfo: userInfo)),
                                                                                    ^^^^^^^^
lib/main.dart:45:100: Error: Can't access 'this' in a field initializer to read 'userInfo'.
    ItemView(title: "Current State", icon: Icons.content_paste, view: CurrentStatesTab(roomNumber: userInfo.location,)),

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    你不能像这样使用实例变量来初始化另一个实例变量。

    class Product {
      final String name;
      final int price = name.length
      
      Product({required this.name});
    }
    

    相反,在构造函数中对其进行初始化:

    class Product {
      final String name;
      final int price;
      
      Product({required this.name}): price = name.length;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-12
      • 2021-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-16
      相关资源
      最近更新 更多