Pass widget key with inherited widget
231
This should be a great read material for you: https://medium.com/coding-with-flutter/flutter-global-access-vs-scoped-access-with-provider-8d6b94393bdf
In my opinion, using InheritedWidget (Provider) or riverpod - which would be scoped access injection - is a good way to go. Your alternative would be to make a global variable, which is a less testable (or not at all testable) approach.
Upd: this is how you pass a key to a Widget:
MyCustomWidget({
required this.widgetData
required final Key key,
}) : super(key: key);
Author by
Mohammed Alfateh
Updated on December 27, 2022Comments
-
Mohammed Alfateh over 1 year
Is there a way to pass widget key by inherited widget (provider,riverPod,InheritedWidget..etc).
If so, what are the pros and cons.
What I want to do is making the widget const (in widget tree) and pass the key as inherited widget since it can't be const because the key is coming from an object.
const MyWidget({ Key key, }):super(key: key);
-
Mohammed Alfateh about 3 yearsThanks for answering Alexey, but what I want to know is how can I set a widget key by inherited widget, I want to know another way to pass key other than widget construct.
-
Alexey Subbotin about 3 yearsAs far as I know, only passing a key to
widget
superclass constructor makes the widget tree accept the key unless you dive deep into flutter framework. I'll update the answer. -
Mohammed Alfateh about 3 yearsIs there another way to pass key rather than using the widget constructor.
-
Alexey Subbotin about 3 yearsThere is no other way. Working with keys in element layer is defined in
Widget
class which is extended by other widget classes, so the superclass must recieve the key through the super call in constructor.