You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter报错The instance member can't be accessed in an initializer如何解决

错误原因

Dart 类的实例属性初始化优先级高于实例构造过程,你在声明_pages列表时直接引用了实例成员counter,此时实例还未完成初始化,counter还处于不可访问状态,就会抛出你遇到的报错。
另外即便你用late关键字绕过初始化校验,提前构建好的_pages列表也不会响应后续counter的数值变化,导致计数器更新后页面不会刷新。

修复方案

将静态声明的_pages列表改为动态getter,每次调用时都基于最新的counter值构建页面组件即可,修改代码如下:
将你原代码中_pages的声明部分:

List<Widget> _pages = <Widget>[
    Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Row(),
        Container(
          padding: EdgeInsets.all(15),
          margin: EdgeInsets.all(10),
          color: Colors.grey[300],
          child: Text(
            'lets see how many times you click it',
            style: TextStyle(
              fontSize: 15,
              fontFamily: 'IndieFlower',
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        Text(
          'button clicks - ${counter}',
          style: TextStyle(
            fontFamily: 'IndieFlower',
            fontWeight: FontWeight.bold,
            color: Colors.blue[600],
            fontSize: 20,
            letterSpacing: 3,
          ),
        ),
      ],
    ),
    Icon(
      Icons.camera,
      size: 150,
    ),
  ];

替换为:

List<Widget> get _pages => <Widget>[
    Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Row(),
        Container(
          padding: EdgeInsets.all(15),
          margin: EdgeInsets.all(10),
          color: Colors.grey[300],
          child: Text(
            'lets see how many times you click it',
            style: TextStyle(
              fontSize: 15,
              fontFamily: 'IndieFlower',
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        Text(
          'button clicks - ${counter}',
          style: TextStyle(
            fontFamily: 'IndieFlower',
            fontWeight: FontWeight.bold,
            color: Colors.blue[600],
            fontSize: 20,
            letterSpacing: 3,
          ),
        ),
      ],
    ),
    Icon(
      Icons.camera,
      size: 150,
    ),
  ];

修改后无需改动其他代码,功能即可正常运行。

内容的提问来源于stack exchange,提问作者Joao Marcos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 10:45:00