1

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?

1 Answer 1

4

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);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.