7

I'd like to know the difference and more importantly the real world usage difference between GlobalKey and GlobalObjectKey, when to use which and when to avoid?

iDecode
  • 22,623
  • 19
  • 99
  • 186

1 Answers1

11

The only difference is how their == operator behaves

final first = GlobalKey();
final second = GlobalKey();
print(first == second); // false
final first = GlobalObjectKey(42);
final second = GlobalObjectKey(42);
final third = GlobalObjectKey(21);
print(first == second); // true
print(first == third); // false

This is important because Flutter relies on comparing a Widget's key using == to see if it should preserve the state of that widget, or instead destroy the previous state and create a new one.

Their usage is slightly different.

GlobalKey would typically be used inside a StatefulWidget, or the key would be stored as a global variable:

class Example extends StatefulWidget {
  @override
  _ExampleState createState() => _ExampleState();
}

class _ExampleState extends State<Example> {
  // Stores the GlobalKey inside the widget State
  final key = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Form(
      key: key,
      child: ...
    );
  }
}

This approach is the most flexible way to use a use a GlobalKey-like. But it is also the most verbose

GlobalObjectKey comes as a simplification to that usage. It allows using global keys inside StatelessWidget for slightly less verbose code, but require a unique "object".

A typical usage would be:

class Example extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final key = const GlobalObjectKey('my_form_key');
    return Form(
      key: key,
      ...
    );
  }
}

This is less verbose. But we need to make sure that the object passed to GlobalObjectKey is unique to this widget and doesn't change over time.

Rémi Rousselet
  • 256,336
  • 79
  • 519
  • 432
  • Thanks for the explanation, however I still didn't understand `GlobalObjectKey` part that good. – iDecode Mar 31 '20 at 09:56