Pass widget key with inherited widget

Viewed 338

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);
1 Answers

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);
Related