unique_widget.dart 1.54 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'framework.dart';
6

7 8 9 10 11 12 13 14 15 16 17 18 19
/// Base class for stateful widgets that have exactly one inflated instance in
/// the tree.
///
/// Such widgets must be given a [GlobalKey]. This key can be generated by the
/// subclass from its [Type] object, e.g. by calling `super(key: new
/// GlobalObjectKey(MyWidget))` where `MyWidget` is the name of the subclass.
///
/// Since only one instance can be inflated at a time, there is only ever one
/// corresponding [State] object. That object is exposed, for convenience, via
/// the [currentState] property.
///
/// When subclassing [UniqueWidget], provide the corresponding [State] subclass
/// as the type argument.
Adam Barth's avatar
Adam Barth committed
20
abstract class UniqueWidget<T extends State<StatefulWidget>> extends StatefulWidget {
21 22
  /// Creates a widget that has exactly one inflated instance in the tree.
  ///
23
  /// The [key] argument must not be null because it identifies the unique
24
  /// inflated instance of this widget.
25
  const UniqueWidget({
26
    required GlobalKey<T> key,
27 28
  }) : assert(key != null),
       super(key: key);
29

30
  @override
Ian Hickson's avatar
Ian Hickson committed
31
  T createState(); // ignore: no_logic_in_create_state, https://github.com/dart-lang/linter/issues/2345
32

33
  /// The state for the unique inflated instance of this widget.
34 35
  ///
  /// Might be null if the widget is not currently in the tree.
36
  T? get currentState {
37
    final GlobalKey<T> globalKey = key! as GlobalKey<T>;
38
    return globalKey.currentState;
Adam Barth's avatar
Adam Barth committed
39
  }
40
}