unique_widget.dart 1.48 KB
Newer Older
1 2 3 4
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'package:flutter/foundation.dart';
6

7
import 'framework.dart';
8

9 10 11 12 13 14 15 16 17 18 19 20 21
/// 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
22
abstract class UniqueWidget<T extends State<StatefulWidget>> extends StatefulWidget {
23 24 25 26 27
  /// Creates a widget that has exactly one inflated instance in the tree.
  ///
  /// The [key] argument cannot be null because it identifies the unique
  /// inflated instance of this widget.
  UniqueWidget({
28
    @required GlobalKey<T> key
29
  }) : super(key: key) {
30 31
    assert(key != null);
  }
32

33
  @override
Adam Barth's avatar
Adam Barth committed
34
  T createState();
35

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