📜  将数据动态保存到文本编辑控制器 - 无论代码示例

📅  最后修改于: 2022-03-11 15:00:11.139000             🧑  作者: Mango

代码示例1
class _MyPetsState extends State {
  List _children = [];
  List controllers = [];  //the controllers list
  int _count = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Title"),
        actions: [IconButton(icon: Icon(Icons.add), onPressed: _add)],
      ),
      body: ListView(children: _children),
    );
  }

  void _add() {

    TextEditingController controller = TextEditingController();
    controllers.add(controller);      //adding the current controller to the list

    for(int i = 0; i < controllers.length; i++){
      print(controllers[i].text);     //printing the values to show that it's working
    }

    _children = List.from(_children)
      ..add(TextFormField(
        controller: controller,
        decoration: InputDecoration(hintText: "This is TextField $_count"),
      ));
    setState(() => ++_count);
  }

  @override
  void dispose() {
    controllers.clear();
    super.dispose();
  }

}