dart - 无法使用 setState

标签 dart flutter

在我的项目中,我使用 ButtomNavigationBar 在两个页面之间切换。 切换的代码是标准的,使用index和setState在两个页面之间切换,使用一个Widget数组访问每个页面。

(取自脚手架)

final List<Widget> body = [ firstPage(), secondPage(), ];

body: body[_currentIndex],

在我的 secondPage() 中,我想制作一个带有 FAB 的 ListView.Builder,每次点击都会添加一个图 block 。 据我所知,我需要使用 setState 来更新 ItemCounter 但这不是正确的 inhertince 我做错了什么,我该如何纠正?

Widget secondPage(){
  int _itemCount = 5;
  return Scaffold(
    body: ListView.builder(
      itemCount: _itemCount,
      itemBuilder: (context, int index){
        return Padding(
          padding: EdgeInsets.all(3.0),
          child: Card(
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text(index.toString(), style: TextStyle(fontSize: 30.0),
              textAlign: TextAlign.center,),
            ),
          ) ,
        );
      },
    ),
    floatingActionButton: FloatingActionButton(
      onPressed:(){}, //**setState need to be here**
    child: Icon(Icons.add),),
  );
}

enter image description here

最佳答案

您正在使用无状态 Widget。您的 secondpage() 应该是有状态的小部件。解决这个问题的最简单方法是使用类而不是函数:

class SecondPage extends StatefulWidget {
  @override
  _SecondPageState createState() => _SecondPageState();
}

class _SecondPageState extends State<SecondPage> {
 int _itemCount = 5;
  return Scaffold(
    body: ListView.builder(
      itemCount: _itemCount,
      itemBuilder: (context, int index){
        return Padding(
          padding: EdgeInsets.all(3.0),
          child: Card(
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text(index.toString(), style: TextStyle(fontSize: 30.0),
              textAlign: TextAlign.center,),
            ),
          ) ,
        );
      },
    ),
    floatingActionButton: FloatingActionButton(
      onPressed:(){
        setState((){
            _itemCount++;
        });
      },
    child: Icon(Icons.add),
    ),
  );
}

在列表中:

final List<Widget> body = [ new firstPage(), new secondPage(), ];

关于dart - 无法使用 setState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55208048/

相关文章:

Flutter StreamBuilder在初始化时称为两次

flutter - 在vscode中使用fvm更改flutter版本,但flutter版本不起作用?

flutter - 如何打开用户终止应用程序的最后一页?

list - Flutter 上传列表到 Google Firestore

google-maps - 通过点击 map 显示坐标

flutter - 如何在Flutter中编写网络通话?

exception - 扩展面板底部溢出

dart - 带有右边框的圆角卡片小部件 flutter

gridview - 如何设置 flutter tablecell 的背景颜色?

json - Flutter GetX中如何使用observable方法处理复杂的API数据响应