我实际想要的是根据列表的每个索引创建文本字段,并在扩展磁贴中显示此文本字段列表,标题为列表的"索引",children
是Textfields
,用户将在单击按钮时动态创建,因此我动态创建了文本字段的列表,现在想将TextEditingController
分配给每个文本字段并重新驱动数据
这是我创建的模型
class MyModel {
List<Widget> widgets;
bool isShow = false;
MyModel({ required this.widgets, required this.isShow});
}
这是我的控制器
class DummyController extends ChangeNotifier {
List<MyModel> myModelList = [];
addTextFieldToDay(var index) {
myModelList[index].widgets.add(TextField());
notifyListeners();
}
}
下面是我如何调用上面的函数并显示文本字段
ListView.builder(
itemCount: vm.myModelList.length,
itemBuilder: ((context, index) {
return ExpansionTile(
title: Text('Day ${index + 1}'),
children: [
IconButton(
onPressed: () {
vm.addTextFieldToDay(index);
},
icon: Icon(Icons.add)),
Container(
color: Colors.white,
height: 150,
child: ListView(children:vm.myModelList[index].widgets)
),
我尝试了所有以前问过的问题解决方案:但我在这方面面临的问题是,我不知道如何获得特定指标控制器的值即
List<TextEditingController> controllers = [];
TextEditingController controller = TextEditingController();
controllers.add(controller);
此处为:
class Home extends StatefulWidget {
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
List<Widget> listData = [];
List<TextEditingController> listDataCTL = [];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('AppBar'),
),
body: Column(
children: [
TextButton(
onPressed: () {
var ctl = TextEditingController(text: "index");
var textF = TextField(
controller: ctl,
);
listData.add(textF);
listDataCTL.add(ctl);
setState(() {});
},
child: Text("Add")),
Expanded(
child: ListView.builder(
itemCount: listData.length + 1,
itemExtent: 50,
itemBuilder: (context, index) {
if (index == 0) {
return GestureDetector(
onTap: () {
print(listDataCTL.first.text);
},
child: Container(
child: Text('Header'),
),
);
}
return Container(
child: listData[index - 1],
);
},
),
),
],
));
}
}
以下是如何实现这一点的:我删除模型类,创建动态类型列表,并使用键值对将天数添加到列表中
class DummyController extends ChangeNotifier {
List days = [];
int addedDay =0;
List finalMap = [];
addDaysToList(){
addedDay++;
days.add({'day$addedDay':<TextEditingController>[]});
finalMap.add({'day$addedDay':<String>[]});
notifyListeners();
}
addTextFieldsToList(var index){
days[index]['day${index+1}'].add(TextEditingController());
notifyListeners();
}}
这就是我在中所做的
Container(
child: SizedBox(
height: 500,
child: ListView.builder(
itemCount: vm.days.length,
itemBuilder: ((context, index) {
return ExpansionTile(
title: Text('Day ${index + 1}'),
children: [
IconButton(
onPressed: () {
vm.addTextFieldsToList(index);
},
icon: Icon(Icons.add)),
Container(
color: Colors.grey[300],
height: 150,
child: ListView.builder(
itemCount: vm.days[index['day${index+1}'].length,
itemBuilder: ((context, mindex) {
return TextField(
controller: vm.days[index]['day${index+1}'][mindex],);
})) ),],);
})),(,(,