Search code examples
flutterdartsetstate

'This expression has a type of 'void' so its value can't be used.' setState() error in Flutter


I am getting the error quoted above when I try to rebuild a class. The class I am calling, ListOfIngs(), is a class that basically creates a textField, but my goal is to create a large amount of TextFields, the variable countIngs holds the value for the exact number, in a listView. Here is the code:

        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);
          }),
        ],
      ),
    )

Solution

  • Try this:

    class ListOfIngs extends State<ListOfIngsWidget> {
      final int countIngs;
      final myController = new TextEditingController();
      ListOfIngs(
        this.countIngs,
      );
      Widget build(BuildContext contex) {
        return new Container(
            child: ListView.builder(
                itemCount: countIngs,
                itemBuilder: (context,index){
                  return Container(
                    child: TextField(
                      controller: myController,
                      decoration: InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: 'Ingredient $index',
                      ),
                    ),
                  );
                },
              ),
           );
      }
    }