0
votes

My flutter ListView doesn't update when my setState runs in my State class.

Yes, My main class is a stateful widget, incase anyone was wondering

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => new _MyAppState();
}

My setState function

setState(() {
        if (price == "null") {
          items.add("Item ${counter + 1}: error");
          print("null");
        } else {
          items.add("Item ${counter + 1}: $price");
          print("$price");
          totalPrice += price;
        }
        counter++;
      });
    });

Before I placed my ListView within a Container -> Column -> Expanded it was working fine. But after I added it, it stopped updating when my setState ran

body: new Container(
         child: Column(
           children: <Widget>[
             Expanded(
               child: ListView.builder(
                 itemCount: items.length,
                 itemBuilder: (context, index) {
                   final item = items[index];

                   return Dismissible(
                     key: Key(item),
                     onDismissed: (direction) {
                       setState(() {
                         items.removeAt(index);
                         counter--;
                       });
                       Scaffold.of(context).showSnackBar(
                           SnackBar(content: Text("$item deleted")));
                     },
                     background: Container(color: Colors.red),
                     child: ListTile(title: Text('$item')),
                   );
                 },
               ),
             ),

Could someone who is more knowledgeable in flutter educate me on what's going on here. I don't think adding the ListView into a container should make that much of a difference to how it works right?

1

1 Answers

0
votes

Doing computations in setstate somehow caused this problem. Instead I did the computations in build since and I used setstate to only add to the list. It’ll then trigger the build and the rest of the things happen there. This solved my problem