Flutter 如何在颤振循环中创建相同的元素?
有没有办法在颤振循环中多次创建相同的元素?用户将输入一个数量(数字),我需要创建相同数量的输入(稍后填充数组)。我已经搜索了几个小时,没有找到任何有用的东西。你可以这样做。我已经在代码中添加了注释,以便您能够理解Flutter 如何在颤振循环中创建相同的元素?,flutter,dart,Flutter,Dart,有没有办法在颤振循环中多次创建相同的元素?用户将输入一个数量(数字),我需要创建相同数量的输入(稍后填充数组)。我已经搜索了几个小时,没有找到任何有用的东西。你可以这样做。我已经在代码中添加了注释,以便您能够理解 import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(B
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: Demo(),
);
}
}
class Demo extends StatefulWidget {
@override
_DemoDataState createState() => _DemoDataState();
}
class _DemoDataState extends State<Demo> {
List<Widget> _listItems = []; // to store the list items
final _textEditingController = TextEditingController();
void addItems(int repeatCount) {
List<Widget> _temp = []; // temporary var to store items
for (int i = 0; i < repeatCount; i++) { // loop till user entered number
_temp.add(Text('Hello again')); // and add our widget to the list
}
// setState() will cause rebuild which will regenerate the list
setState(() {
_listItems.addAll(_temp); // finally add the _temp items into our main ( _listItems ) list variable
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
title: Text(
"Demo",
style: TextStyle(fontSize: 20, color: Colors.white),
),
),
backgroundColor: Colors.white,
body: SingleChildScrollView(
child: Column(children: [
TextField(
controller: _textEditingController,
onSubmitted: (String value) async { // after user number enters and click on done, this will be called
if (value != null) {
addItems(int.parse(value)); // call the method to add number of element with user entered number
}
}),
ListView.builder(
shrinkWrap: true,
itemCount: _listItems.length,
itemBuilder: (context, index) {
return Text('Hello $index'); // show the item
})
])));
}
}
导入“包装:颤振/材料.省道”;
void main(){
runApp(MyApp());
}
类MyApp扩展了无状态小部件{
@凌驾
小部件构建(构建上下文){
返回材料PP(
标题:“颤振演示”,
主页:Demo(),
);
}
}
类Demo扩展StatefulWidget{
@凌驾
_DemoDataState createState()=>\u DemoDataState();
}
类_DemoDataState扩展状态{
List _listItems=[];//存储列表项
最终_textEditingController=textEditingController();
无效附加项(整数重复计数){
列表_temp=[];//存储项的临时变量
对于(int i=0;i
您可以通过以下几个步骤实现所需的逻辑:
StatefulWidget
int数量=0
你能详细说明一下吗?我需要的是TextFiels没有任何效果,我在他们的控制器上遇到了问题,但谢谢你们的帮助
Column(
children:[
for( int i = 0 ; i < quantity ; i++)
// Here add the widget you created for the single item...
// e.g.
Container(
width: double.infinity,
height: 100,
color: Colors.red
)
]
), // Note: Initially it will not create
// any widget because we initialized the quantity variable with 0...
TextField(
...
onChanged: (value){
setState((){
quantity = int.parse(value);
// Note this line can fail when the user
// enters a non-number value, so be careful and add the validation...
});
}
),