Zahra
Zahra

Reputation: 426

What is the difference between accessing the Global Keys using InheritedWidget and defining them Globally?

Using InheritedWidget I need to doKeysToBeInherited.of(context).homeKey1 for using the keys in different parts of the app:

    class ShowcaseStatefulWidget extends StatefulWidget {
  @override
  _ShowcaseStatefulWidgetState createState() => _ShowcaseStatefulWidgetState();
}

class _ShowcaseStatefulWidgetState extends State<ShowcaseStatefulWidget> {

  final GlobalKey _homeKey1 = GlobalKey();
  final GlobalKey _homeKey2 = GlobalKey();
  final GlobalKey _homeKey3 = GlobalKey();
  final GlobalKey _storeKey1 = GlobalKey();
  final GlobalKey _storeKey2 = GlobalKey();
  final GlobalKey _storeKey3 = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return KeysToBeInherited(
       homeKey1: _homeKey1,
       homeKey2: _homeKey2,
       homeKey3: _homeKey3,
       storeKey1: _storeKey1,
       storeKey2: _storeKey2,
       storeKey3: _storeKey3,
      child: AppRoutes(),
    );
  }
}

class KeysToBeInherited extends InheritedWidget {
  KeysToBeInherited({
    required this.homeKey1,
    required this.homeKey2,
    required this.homeKey3,
    required this.storeKey1,
    required this.storeKey2,
    required this.storeKey3,
  }) : super(child: child);

  final GlobalKey homeKey1;
  final GlobalKey homeKey2;
  final GlobalKey homeKey3;
  final GlobalKey storeKey1;
  final GlobalKey storeKey2;
  final GlobalKey storeKey3;


  static KeysToBeInherited? of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<KeysToBeInherited>();
  }

  @override
  bool updateShouldNotify(InheritedWidget oldWidget) {
    return true;
  }
}

Or defining the like:

  final GlobalKey homeKey1 = GlobalKey();
  final GlobalKey homeKey2 = GlobalKey();
  final GlobalKey homeKey3 = GlobalKey();
  final GlobalKey storeKey1 = GlobalKey();
  final GlobalKey storeKey2 = GlobalKey();
  final GlobalKey storeKey3 = GlobalKey();

Both approche work and I am not sure which one should I pick, and what are the prose and cons of using either approch?

ShowcaseStatefulWidget does not ncessarily need to be statefull. The AppRoute() is where I define Matterial app and the routes.

Upvotes: 0

Views: 173

Answers (1)

reza
reza

Reputation: 1508

if your keys are constant use the second approach and if your keys might change and you need your children to be notified, use the first approach.

Upvotes: 1

Related Questions