Flutter接入底部导航栏后初始化器无法访问posts实例成员报错如何解决
Flutter报错「The instance member 'posts' can't be accessed in an initializer」解决方案
报错原因
你在State类中直接声明并初始化了_widgetOptions列表,Dart类实例的属性初始化阶段,实例本身还未完成创建,因此无法访问同属实例成员的posts变量,触发语法报错。
修复步骤
- 首先修改
_widgetOptions的声明方式,不再直接初始化:
把原代码中类属性位置的定义
List _widgetOptions = [ // 页面代码 ];
修改为:
late List<Widget> _widgetOptions;
- 在
initState方法中完成_widgetOptions的初始化,把原页面代码移到该方法内:
@override void initState() { super.initState(); loading = true; // 初始化底部导航对应页面列表 _widgetOptions = [ Column( children: [ Container( color: Colors.amber, child: Row( children: const [ Expanded( child: Center( child: Text('Date', style: TextStyle( height: 2.5, fontSize: 18, fontWeight: FontWeight.bold, leadingDistribution: TextLeadingDistribution.even, )))), Expanded( child: Center( child: Text('Koreanwon/us\$', style: TextStyle( height: 2.5, fontSize: 18, fontWeight: FontWeight.bold, leadingDistribution: TextLeadingDistribution.even, )))), Expanded( child: Center( child: Text('Koreanwon', style: TextStyle( height: 2.5, fontSize: 18, fontWeight: FontWeight.bold, leadingDistribution: TextLeadingDistribution.even, )))), Expanded( child: Center( child: Text('US \$', style: TextStyle( height: 2.5, fontSize: 18, fontWeight: FontWeight.bold, leadingDistribution: TextLeadingDistribution.even, )))), ], ), ), Expanded( child: Center( child: Container( child: ListView.builder( itemCount: posts == null ? 0 : posts.length, itemBuilder: (context, index) { Post post = posts[index]; return Container( decoration: const BoxDecoration( border: Border( bottom: BorderSide(color: Colors.blueAccent)), ), child: ListTile( title: Row( children: <Widget>[ Expanded(child: Center(child: Text(post.date))), Expanded(child: Center(child: Text(post.rate))), Expanded( child: Center(child: Text(post.koreanwon))), Expanded(child: Center(child: Text(post.dollar))), ], ), ), ); }), ), ), ), ], ), // 剩余三个导航页可后续补充对应Widget即可 const Center(child: Text('音乐页')), const Center(child: Text('地点页')), const Center(child: Text('新闻页')), ]; Services.getPosts().then((list) { setState(() { posts = list; loading = false; }); }); }
- 附加优化建议
你当前声明posts时使用了late关键字,但是代码中仍保留了posts == null的判空逻辑,late修饰的变量默认不会为空,建议把late List<Post> posts;修改为List<Post>? posts;,避免触发空安全异常。
内容的提问来源于stack exchange,提问作者OE SEOK HWANG
相关产品推荐
相关产品推荐

