当我尝试重建一个类时,出现上述错误。我正在调用的类ListOfIngs()是一个基本上创建textField的类,但是我的目标是创建大量TextField,变量countIngs在listView中保存确切数字的值。这是代码:

class NewGroceryList extends State<NewGroceryListWidget> {
  final GlobalKey<_ListOfIngsState> _key = GlobalKey();
  final myController = new TextEditingController();
  int countings = 0;
  Widget build(BuildContext context) {
    debugPrint(myController.text);
    return Scaffold(
        appBar: AppBar(
          title: Text("New Grocery List"),
          leading: IconButton(
            icon: const Icon(Icons.arrow_back_ios, color: Colors.white),
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => ListsPage()),
              );
            },
          ),
          actions: <Widget>[
            IconButton(
                icon: new Icon(Icons.check, color: Colors.white),
                onPressed: () {})
          ],
        ),
        drawer: AppDrawer(),
        body: Container(
          padding: EdgeInsets.fromLTRB(10.0, 20.0, 10.0, 30.0),
          child: Column(
            children: <Widget>[
              Row(
                children: <Widget>[
                  Text('Ingredients',
                      style: GoogleFonts.biryani(fontSize: 15.0)),
                  IconButton(
                    icon: new Icon(Icons.add),
                    onPressed: () {
                      setState(() {
                        countings++;
                      });
                      debugPrint('$countings');
                    },
                  )
                ],
              ),
              setState(() {
                ListOfIngsWidget(countings);
              }),
            ],
          ),
        ));
  }
}
这是ListOfIngs类/小部件:
ListOfIngsWidget类扩展StatefulWidget {
最终的int计数
  const ListOfIngsWidget(this.countIngs, {Key key}) : super(key: key);

  @override
  _ListOfIngsState createState() => _ListOfIngsState();
}

class _ListOfIngsState extends State<ListOfIngsWidget> {
  List<TextEditingController> _controllerList = [];
  List<TextField> _textFieldList = [];

  @override
  void initState() {
    for (int i = 1; i <= widget.countIngs; i++) {
      TextEditingController controller = TextEditingController();
      TextField textField = TextField(
        controller: controller,
        decoration: InputDecoration(
          border: OutlineInputBorder(),
          labelText: 'Ingredient $i',
        ),
      );
      _textFieldList.add(textField);
      _controllerList.add(controller);
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return new Container(
      child: Flexible(
        child: ListView(children: _textFieldList),
      ),
    );
  }
}

最佳答案

删除setState周围的ListOfIngsWidget,然后向其添加UniqueKey(),如下所示:ListOfIngsWidget(countings, key: UniqueKey())

关于flutter - “此表达式的类型为 'void',因此无法使用其值。” setState()错误抖动,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62685701/

10-14 12:51