在我的项目中,我使用 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),),
);
}
最佳答案
您正在使用无状态 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/