Flutter应用程序创建一个窗口小部件列表(wList)并正确显示屏幕。如果用户按下按钮,它将向wList添加一个divider()并通过setState()更新屏幕。但是,屏幕没有更新。我想我可能不太了解setState的逻辑。如果我更新wList并调用setState()函数,我认为它应该更新屏幕。但事实并非如此。
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text('檯號: ${widget.inputTableNumber}'),
centerTitle: true,
backgroundColor: Colors.black,
actions: <Widget>[
IconButton(icon: Icon(Icons.edit), onPressed: () => _showButtons(), color: Colors.white,)
],
),
body: RepaintBoundary(
key: _renderInvoice,
child: Padding(
padding: EdgeInsets.all(15.0),
child: ListView(
children: wList,
),
)
)
);
}
_showButtons() {
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) {
return Container(
color: Colors.white54,
height: 500.0,
child: GridView.count(
primary: false,
padding: const EdgeInsets.all(20.0),
crossAxisSpacing: 30.0,
mainAxisSpacing: 30.0,
crossAxisCount: 3,
children: <Widget>[
FloatingActionButton(
onPressed: () {_addPercentage(0.1);},
heroTag: null,
backgroundColor: Colors.purpleAccent,
child: Text('+10%', style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.w500)),
foregroundColor: Colors.black,
),
],
)
);
});
}
_addPercentage(double d) {
Navigator.pop(context);
setState(() {
wList.add(Divider(color: Colors.black,));
});
}
所以这个失败的原因是因为标准的Listview
构造函数需要一个const
children参数。显然,你的wList
不是const
值,并且在按下按钮时会发生变化。
相反,你应该像这样使用Listview.builder
:
ListView.builder(
itemCount: wList.length,
itemBuilder: (context, index) {
return wList[index];
}
)