Issue
I have stateful widget class and it's state class. I have gridview widget in state class and list of widgets -in state class- belongs to gridview children. I want to update state when i changed my list of widgets because if i don't ui doesn't changes. How can i do that or what is the correct way?
class UIHandler extends StatefulWidget {
const UIHandler({ Key? key}) : super(key: key);
static List<Widget> widgets = [];
void someFunc() { /* Do some changes on widgets list but that doens't changes ui so i want to update state */}
..
}
class _UIHandlerState extends State<UIHandler> {
@override
Widget build(BuildContext context) {
return GridView.count(
children: List.of(UIHandler.widgets),
);
}
}
Solution
Ideally, there should not be any logic in StatefulWidget. The list of widgets should be maintained outside the stateful widget and passed via the constructor. The UI is automatically rebuilt when the list of widgets passed changes.
However to access the state within the widget use a global key for the widget. The current state can be accessed using it.
class UIHandler extends StatefulWidget {
// create a global key
static final _uiHandlerKey = GlobalKey<_UIHandlerState>();
// use the global key here
UIHandler() : super(key: _uiHandlerKey);
static List<Widget> widgets = [];
void someFunc() {
// access the current state of the widget
final state = _uiHandlerKey.currentState;
if (state != null) {
state.callSetState();
}
}
}
class _UIHandlerState extends State<UIHandler> {
// because setState is protected
void callSetState() {
setState(() {});
}
@override
Widget build(BuildContext context) {
return GridView.count(
children: List.of(UIHandler.widgets),
);
}
}
Since we are using the same GlobalKey
for all instances of UIHandler
, there can only be one UIHandler at any time.
Answered By - Navaneeth P
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.