我有一個ListView,我想在每次按下Button的時候添加一個新的Text Widget。當按鈕被按下時,用戶應該能夠在文本Widget中插入字串。有什么方法可以做到這一點嗎?
ListView(children: [
//New Widget here evertime the Button is pressed.
]),
ElevatedButton(onPressed: ()
{
//當這個按鈕被按下時添加新專案。
}
, child: Text("Add Item") )
uj5u.com熱心網友回復:
代替ListView你應該使用一個ListView.builder,和一個List<Widget>變數_strings來存盤所有的新字串。下面是一個示例代碼:
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState()。
}
class _MyAppState extends State< MyApp> {
List<Widget> _strings = [];
@override
Widget build(BuildContext context) {
return MaterialApp(
標題。'Flutter Demo'。
首頁。Scaffold(
body: Column(
兒童。[
擴展的(
child: ListView.builder(
itemCount: _strings.length,
itemBuilder: (context, index) => _strings[index],
),
),
提升的按鈕(
onPressed: () {
設定狀態(
() {
_strings.add(
Text('new text added')。
);
},
);
},
孩子。Text('Add String')。
)
],
),
),
);
}
}
CodePudding
使用一個ListViewBuilder來代替一個StatefulWidget,我建議在Scaffold Widget中使用一個FloatingActionButton。
class MyApp extends StatefulWidget {
const MyApp()。
_MyAppState createState() => _MyAppState()。
}
class _MyAppState extends State< MyApp> {
List<String> list = [] 。
_onPressed(String val) {
setState((){
list.add(val);
});
_listViewBuilder() {
return ListView.builder(
itemCount: list.length,
itemBuilder: (context, index) {
return Text(list[index])。
});
}
@override
Widget build(BuildContext context){
架構(Scaffold)
appBar: AppBar(
標題。Text(widget.title),
),
body: _listViewBuilder()。
floatingActionButton: FloatingActionButton(
onPressed: (){
_onPressed("Text To Add")。
},
tooltip: 'add',
孩子。const Icon(Icons.add)。
),
);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/315677.html
標籤:
