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?
- Saving the reference to the state without violating
no_logic_in_create_state
. - Accessing the state from the widget, without saving the reference.
- Calling the method of the state from the outside without going through the widget.