Vedavyas Bhat
Vedavyas Bhat

Reputation: 2108

Flutter UI doesn't update when custom widget is used

I have a Flutter where I display a list of elements in a Column, where the each item in the list is a custom widget. When I update the list, my UI doesn't refresh.

Working sample:

class Test extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return TestState();
  }
}

class TestState extends State<Test> {

  List<String> list = ["one", "two"];
  final refreshKey = new GlobalKey<RefreshIndicatorState>();

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      body: Container(
        padding: EdgeInsets.all(40),
        child: Row(
          children: <Widget>[
            Container(
              child: FlatButton(
                child: Text("Update"),
                onPressed: () {
                  print("Updating list");
                  setState(() {
                    list = ["three", "four"];
                  });
                },
              )
            ),
            Column(
              children: list.map((s) => ItemView(s)).toList(),
            )
          ],
        ),
      )
    );
  }
}

class ItemView extends StatefulWidget {
  String s;

  ItemView(this.s);

  @override
  State<StatefulWidget> createState() => ItemViewState(s);
}

class ItemViewState extends State<ItemView> {
  String s;

  ItemViewState(this.s);

  @override
  Widget build(BuildContext context) {
    return Text(s);
  }
}

When I press the "Update" button, my list is updated but the UI is not. I believe this has something to do with using a custom widget (which is also stateful) because when I replace ItemView(s) with the similar Text(s), the UI updates.

I understand that Flutter keeps a track of my stateful widgets and what data is being used, but I'm clearly missing something.

How do I get the UI to update and still use my custom widget?

Upvotes: 1

Views: 775

Answers (1)

R&#233;mi Rousselet
R&#233;mi Rousselet

Reputation: 276911

You should never pass parameters to your State.

Instead, use the widget property.

class ItemView extends StatefulWidget {
  String s;

  ItemView(this.s);

  @override
  State<StatefulWidget> createState() => ItemViewState();
}

class ItemViewState extends State<ItemView> {
  @override
  Widget build(BuildContext context) {
    return Text(widget.s);
  }
}

Upvotes: 4

Related Questions