0

Using Flutter, I display a list of elements in an app.

I have a StatefulWidget (ObjectList) that holds a list of items in its State (ObjectListState).

The state has a method (_populateList) to update the list of items.

I want the list to be updated when a method (updateList) is called on the widget.

To achieve this, I save a reference (_state) to the state in the widget. The value is set in createState. Then the method on the state can be called from the widget itself.


class ObjectList extends StatefulWidget {
  const ObjectList({super.key});

  static late ObjectListState _state;

  @override
  State<ObjectList> createState() {
    _state = ObjectListState();
    return _state;
  }

  void updateList() {
    _state._populateList();
  }
}


class ObjectListState extends State<ObjectList> {
  List<Object>? objects;

  void _populateList() {
    setState(() {
      // objects = API().getObjects();
    });
  }

  // ... return ListView in build
}

The problem is that this raises a no_logic_in_create_state warning. Since I'm not "passing data to State objects" I assume this is fine, but I would still like to avoid the warning.

Is there a way to do any of these?

  1. Saving the reference to the state without violating no_logic_in_create_state.
  2. Accessing the state from the widget, without saving the reference.
  3. Calling the method of the state from the outside without going through the widget.
Nereos
  • 101
  • 6

1 Answers1

0

It make no sense to put the updateList() method in the widget. You will not be able to call it anyway. Widgets are part of a widget tree, and you do not store or use a reference to them (unlike in other frameworks, such as Qt).

To update information in a widget, use a StreamBuilder widget and create the widget to be updated in the build function, passing the updated list to as a parameter to the widget.

Then, you store the list inside the widget. Possibly this may then be implemented as a stateless widget.

Ber
  • 40,356
  • 16
  • 72
  • 88