如何在Flutter中添加TextEditingController并从动态TextFormField获得文本值?

问题描述 投票:0回答:1

我想从这些动态TextFormField获得文本值

class MyPets extends StatefulWidget {
  @override
  _MyPetsState createState() => _MyPetsState();
}

class _MyPetsState extends State<MyPets> {
  List<Widget> _children = [];
  int _count = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Title"),
        actions: <Widget>[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",
            icon: IconButton(icon: Icon(Icons.remove_circle), onPressed: rem),
          ),
        ),
      );
    setState(() => ++_count);
  }

  rem() {
    setState(() {
      _children.removeAt(_count);
      controllers.removeAt(_count);
    });
  }

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

问题是我不知道如何在Flutter中将TextEditingController传递到此表单域我从this stack overflow answer]获得了以上解决方案

基本上我想要文本字段,当我点击按钮时,文本字段必须递增我想要每个文本字段中的值,我也应该能够删除相应的字段

请帮助我在此先感谢

我想从这些动态TextFormField类获得文本值MyPets扩展了StatefulWidget {@override _MyPetsState createState()=> _MyPetsState(); }类_MyPetsState扩展了State&...

flutter dart flutter-layout
1个回答
0
投票

您可以动态获取所有这些字段的值,将控制器添加到列表中:

© www.soinside.com 2019 - 2024. All rights reserved.