1 | // Copyright 2014 The Flutter Authors. All rights reserved. |
2 | // Use of this source code is governed by a BSD-style license that can be |
3 | // found in the LICENSE file. |
4 | |
5 | import 'framework.dart'; |
6 | |
7 | /// Base class for stateful widgets that have exactly one inflated instance in |
8 | /// the tree. |
9 | /// |
10 | /// Such widgets must be given a [GlobalKey]. This key can be generated by the |
11 | /// subclass from its [Type] object, e.g. by calling `super(key: new |
12 | /// GlobalObjectKey(MyWidget))` where `MyWidget` is the name of the subclass. |
13 | /// |
14 | /// Since only one instance can be inflated at a time, there is only ever one |
15 | /// corresponding [State] object. That object is exposed, for convenience, via |
16 | /// the [currentState] property. |
17 | /// |
18 | /// When subclassing [UniqueWidget], provide the corresponding [State] subclass |
19 | /// as the type argument. |
20 | abstract class UniqueWidget<T extends State<StatefulWidget>> extends StatefulWidget { |
21 | /// Creates a widget that has exactly one inflated instance in the tree. |
22 | /// |
23 | /// The [key] argument is required because it identifies the unique inflated |
24 | /// instance of this widget. |
25 | const UniqueWidget({ |
26 | required GlobalKey<T> key, |
27 | }) : super(key: key); |
28 | |
29 | @override |
30 | T createState(); |
31 | |
32 | /// The state for the unique inflated instance of this widget. |
33 | /// |
34 | /// Might be null if the widget is not currently in the tree. |
35 | T? get currentState { |
36 | final GlobalKey<T> globalKey = key! as GlobalKey<T>; |
37 | return globalKey.currentState; |
38 | } |
39 | } |
40 | |