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?
no_logic_in_create_state
.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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.