async.dart 25 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
// Copyright 2017 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.

/// Widgets that handle interaction with asynchronous computations.
///
/// Asynchronous computations are represented by [Future]s and [Stream]s.

import 'dart:async' show Future, Stream, StreamSubscription;

11
import 'framework.dart';
12

13 14
// Examples can assume:
// dynamic _lot;
15
// Future<String> _calculation;
16

17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
/// Base class for widgets that build themselves based on interaction with
/// a specified [Stream].
///
/// A [StreamBuilderBase] is stateful and maintains a summary of the interaction
/// so far. The type of the summary and how it is updated with each interaction
/// is defined by sub-classes.
///
/// Examples of summaries include:
///
/// * the running average of a stream of integers;
/// * the current direction and speed based on a stream of geolocation data;
/// * a graph displaying data points from a stream.
///
/// In general, the summary is the result of a fold computation over the data
/// items and errors received from the stream along with pseudo-events
/// representing termination or change of stream. The initial summary is
/// specified by sub-classes by overriding [initial]. The summary updates on
/// receipt of stream data and errors are specified by overriding [afterData] and
/// [afterError], respectively. If needed, the summary may be updated on stream
/// termination by overriding [afterDone]. Finally, the summary may be updated
37
/// on change of stream by overriding [afterDisconnected] and [afterConnected].
38
///
39
/// `T` is the type of stream events.
40
///
41
/// `S` is the type of interaction summary.
42 43 44
///
/// See also:
///
45 46
///  * [StreamBuilder], which is specialized for the case where only the most
///    recent interaction is needed for widget building.
47 48
abstract class StreamBuilderBase<T, S> extends StatefulWidget {
  /// Creates a [StreamBuilderBase] connected to the specified [stream].
49
  const StreamBuilderBase({ Key key, this.stream }) : super(key: key);
50 51

  /// The asynchronous computation to which this builder is currently connected,
52
  /// possibly null. When changed, the current summary is updated using
53 54
  /// [afterDisconnected], if the previous stream was not null, followed by
  /// [afterConnected], if the new stream is not null.
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
  final Stream<T> stream;

  /// Returns the initial summary of stream interaction, typically representing
  /// the fact that no interaction has happened at all.
  ///
  /// Sub-classes must override this method to provide the initial value for
  /// the fold computation.
  S initial();

  /// Returns an updated version of the [current] summary reflecting that we
  /// are now connected to a stream.
  ///
  /// The default implementation returns [current] as is.
  S afterConnected(S current) => current;

  /// Returns an updated version of the [current] summary following a data event.
  ///
  /// Sub-classes must override this method to specify how the current summary
  /// is combined with the new data item in the fold computation.
  S afterData(S current, T data);

  /// Returns an updated version of the [current] summary following an error.
  ///
  /// The default implementation returns [current] as is.
  S afterError(S current, Object error) => current;

  /// Returns an updated version of the [current] summary following stream
  /// termination.
  ///
  /// The default implementation returns [current] as is.
  S afterDone(S current) => current;

  /// Returns an updated version of the [current] summary reflecting that we
  /// are no longer connected to a stream.
  ///
  /// The default implementation returns [current] as is.
  S afterDisconnected(S current) => current;

  /// Returns a Widget based on the [currentSummary].
  Widget build(BuildContext context, S currentSummary);

  @override
97
  State<StreamBuilderBase<T, S>> createState() => _StreamBuilderBaseState<T, S>();
98 99 100 101 102 103 104 105 106 107
}

/// State for [StreamBuilderBase].
class _StreamBuilderBaseState<T, S> extends State<StreamBuilderBase<T, S>> {
  StreamSubscription<T> _subscription;
  S _summary;

  @override
  void initState() {
    super.initState();
108
    _summary = widget.initial();
109 110 111 112
    _subscribe();
  }

  @override
113
  void didUpdateWidget(StreamBuilderBase<T, S> oldWidget) {
114
    super.didUpdateWidget(oldWidget);
115
    if (oldWidget.stream != widget.stream) {
116 117
      if (_subscription != null) {
        _unsubscribe();
118
        _summary = widget.afterDisconnected(_summary);
119 120 121 122 123 124
      }
      _subscribe();
    }
  }

  @override
125
  Widget build(BuildContext context) => widget.build(context, _summary);
126 127 128 129 130 131 132 133

  @override
  void dispose() {
    _unsubscribe();
    super.dispose();
  }

  void _subscribe() {
134 135
    if (widget.stream != null) {
      _subscription = widget.stream.listen((T data) {
136
        setState(() {
137
          _summary = widget.afterData(_summary, data);
138 139 140
        });
      }, onError: (Object error) {
        setState(() {
141
          _summary = widget.afterError(_summary, error);
142 143 144
        });
      }, onDone: () {
        setState(() {
145
          _summary = widget.afterDone(_summary);
146 147
        });
      });
148
      _summary = widget.afterConnected(_summary);
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
    }
  }

  void _unsubscribe() {
    if (_subscription != null) {
      _subscription.cancel();
      _subscription = null;
    }
  }
}

/// The state of connection to an asynchronous computation.
///
/// See also:
///
164 165
///  * [AsyncSnapshot], which augments a connection state with information
///    received from the asynchronous computation.
166 167
enum ConnectionState {
  /// Not currently connected to any asynchronous computation.
168 169
  ///
  /// For example, a [FutureBuilder] whose [FutureBuilder.future] is null.
170 171 172 173 174 175
  none,

  /// Connected to an asynchronous computation and awaiting interaction.
  waiting,

  /// Connected to an active asynchronous computation.
176 177 178
  ///
  /// For example, a [Stream] that has returned at least one value, but is not
  /// yet done.
179 180 181 182 183 184 185 186 187 188 189
  active,

  /// Connected to a terminated asynchronous computation.
  done,
}

/// Immutable representation of the most recent interaction with an asynchronous
/// computation.
///
/// See also:
///
190 191 192 193
///  * [StreamBuilder], which builds itself based on a snapshot from interacting
///    with a [Stream].
///  * [FutureBuilder], which builds itself based on a snapshot from interacting
///    with a [Future].
194
@immutable
195
class AsyncSnapshot<T> {
196 197 198
  /// Creates an [AsyncSnapshot] with the specified [connectionState],
  /// and optionally either [data] or [error] (but not both).
  const AsyncSnapshot._(this.connectionState, this.data, this.error)
199
    : assert(connectionState != null),
200
      assert(!(data != null && error != null));
201

202 203
  /// Creates an [AsyncSnapshot] in [ConnectionState.none] with null data and error.
  const AsyncSnapshot.nothing() : this._(ConnectionState.none, null, null);
204

205 206
  /// Creates an [AsyncSnapshot] in the specified [state] and with the specified [data].
  const AsyncSnapshot.withData(ConnectionState state, T data) : this._(state, data, null);
207

208 209
  /// Creates an [AsyncSnapshot] in the specified [state] and with the specified [error].
  const AsyncSnapshot.withError(ConnectionState state, Object error) : this._(state, null, error);
210

211
  /// Current state of connection to the asynchronous computation.
212 213
  final ConnectionState connectionState;

214
  /// The latest data received by the asynchronous computation.
215
  ///
216
  /// If this is non-null, [hasData] will be true.
217
  ///
218
  /// If [error] is not null, this will be null. See [hasError].
219
  ///
220 221 222 223 224 225
  /// If the asynchronous computation has never returned a value, this may be
  /// set to an initial data value specified by the relevant widget. See
  /// [FutureBuilder.initialData] and [StreamBuilder.initialData].
  final T data;

  /// Returns latest data received, failing if there is no data.
226
  ///
227 228 229
  /// Throws [error], if [hasError]. Throws [StateError], if neither [hasData]
  /// nor [hasError].
  T get requireData {
230
    if (hasData)
231 232
      return data;
    if (hasError)
233
      throw error;
234
    throw StateError('Snapshot has neither data nor error');
235 236
  }

237 238 239 240 241
  /// The latest error object received by the asynchronous computation.
  ///
  /// If this is non-null, [hasError] will be true.
  ///
  /// If [data] is not null, this will be null.
242 243 244
  final Object error;

  /// Returns a snapshot like this one, but in the specified [state].
245
  ///
246 247 248 249 250 251 252 253 254 255 256
  /// The [data] and [error] fields persist unmodified, even if the new state is
  /// [ConnectionState.none].
  AsyncSnapshot<T> inState(ConnectionState state) => AsyncSnapshot<T>._(state, data, error);

  /// Returns whether this snapshot contains a non-null [data] value.
  ///
  /// This can be false even when the asynchronous computation has completed
  /// successfully, if the computation did not return a non-null value. For
  /// example, a [Future<void>] will complete with the null value even if it
  /// completes successfully.
  bool get hasData => data != null;
257

258 259 260 261
  /// Returns whether this snapshot contains a non-null [error] value.
  ///
  /// This is always true if the asynchronous computation's last result was
  /// failure.
262 263 264
  bool get hasError => error != null;

  @override
265
  String toString() => '$runtimeType($connectionState, $data, $error)';
266 267 268 269 270

  @override
  bool operator ==(dynamic other) {
    if (identical(this, other))
      return true;
271
    if (other is! AsyncSnapshot<T>)
272 273 274
      return false;
    final AsyncSnapshot<T> typedOther = other;
    return connectionState == typedOther.connectionState
275
        && data == typedOther.data
276 277 278 279
        && error == typedOther.error;
  }

  @override
280
  int get hashCode => hashValues(connectionState, data, error);
281 282 283 284 285 286 287
}

/// Signature for strategies that build widgets based on asynchronous
/// interaction.
///
/// See also:
///
288 289 290 291
///  * [StreamBuilder], which delegates to an [AsyncWidgetBuilder] to build
///    itself based on a snapshot from interacting with a [Stream].
///  * [FutureBuilder], which delegates to an [AsyncWidgetBuilder] to build
///    itself based on a snapshot from interacting with a [Future].
292
typedef AsyncWidgetBuilder<T> = Widget Function(BuildContext context, AsyncSnapshot<T> snapshot);
293 294 295 296

/// Widget that builds itself based on the latest snapshot of interaction with
/// a [Stream].
///
297 298
/// {@youtube 560 315 https://www.youtube.com/watch?v=MkKEWHfy99Y}
///
299
/// Widget rebuilding is scheduled by each interaction, using [State.setState],
300
/// but is otherwise decoupled from the timing of the stream. The [builder]
301 302 303 304 305
/// is called at the discretion of the Flutter pipeline, and will thus receive a
/// timing-dependent sub-sequence of the snapshots that represent the
/// interaction with the stream.
///
/// As an example, when interacting with a stream producing the integers
306
/// 0 through 9, the [builder] may be called with any ordered sub-sequence
307 308 309
/// of the following snapshots that includes the last one (the one with
/// ConnectionState.done):
///
310 311 312
/// * `new AsyncSnapshot<int>.withData(ConnectionState.waiting, null)`
/// * `new AsyncSnapshot<int>.withData(ConnectionState.active, 0)`
/// * `new AsyncSnapshot<int>.withData(ConnectionState.active, 1)`
313
/// * ...
314 315
/// * `new AsyncSnapshot<int>.withData(ConnectionState.active, 9)`
/// * `new AsyncSnapshot<int>.withData(ConnectionState.done, 9)`
316
///
317 318 319
/// The actual sequence of invocations of the [builder] depends on the relative
/// timing of events produced by the stream and the build rate of the Flutter
/// pipeline.
320 321
///
/// Changing the [StreamBuilder] configuration to another stream during event
322
/// generation introduces snapshot pairs of the form:
323
///
324 325
/// * `new AsyncSnapshot<int>.withData(ConnectionState.none, 5)`
/// * `new AsyncSnapshot<int>.withData(ConnectionState.waiting, 5)`
326
///
327 328
/// The latter will be produced only when the new stream is non-null, and the
/// former only when the old stream is non-null.
329
///
330
/// The stream may produce errors, resulting in snapshots of the form:
331
///
332
/// * `new AsyncSnapshot<int>.withError(ConnectionState.active, 'some error')`
333 334 335 336
///
/// The data and error fields of snapshots produced are only changed when the
/// state is `ConnectionState.active`.
///
337
/// The initial snapshot data can be controlled by specifying [initialData].
338 339
/// This should be used to ensure that the first frame has the expected value,
/// as the builder will always be called before the stream listener has a chance
340
/// to be processed.
341
///
342
/// {@tool sample}
343 344 345 346 347 348
///
/// This sample shows a [StreamBuilder] configuring a text label to show the
/// latest bid received for a lot in an auction. Assume the `_lot` field is
/// set by a selector elsewhere in the UI.
///
/// ```dart
349
/// StreamBuilder<int>(
350 351 352
///   stream: _lot?.bids, // a Stream<int> or null
///   builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
///     if (snapshot.hasError)
353
///       return Text('Error: ${snapshot.error}');
354
///     switch (snapshot.connectionState) {
355 356 357 358
///       case ConnectionState.none: return Text('Select lot');
///       case ConnectionState.waiting: return Text('Awaiting bids...');
///       case ConnectionState.active: return Text('\$${snapshot.data}');
///       case ConnectionState.done: return Text('\$${snapshot.data} (closed)');
359
///     }
360
///     return null; // unreachable
361
///   },
362
/// )
363
/// ```
364
/// {@end-tool}
365 366 367 368 369 370 371 372
///
/// See also:
///
///  * [ValueListenableBuilder], which wraps a [ValueListenable] instead of a
///    [Stream].
///  * [StreamBuilderBase], which supports widget building based on a computation
///    that spans all interactions made with the stream.
// TODO(ianh): remove unreachable code above once https://github.com/dart-lang/linter/issues/1139 is fixed
373 374
class StreamBuilder<T> extends StreamBuilderBase<T, AsyncSnapshot<T>> {
  /// Creates a new [StreamBuilder] that builds itself based on the latest
375
  /// snapshot of interaction with the specified [stream] and whose build
376 377
  /// strategy is given by [builder].
  ///
378
  /// The [initialData] is used to create the initial snapshot.
379 380
  ///
  /// The [builder] must not be null.
381
  const StreamBuilder({
382
    Key key,
383
    this.initialData,
384
    Stream<T> stream,
385
    @required this.builder,
386 387
  }) : assert(builder != null),
       super(key: key, stream: stream);
388

389
  /// The build strategy currently used by this builder.
390 391
  final AsyncWidgetBuilder<T> builder;

392 393
  /// The data that will be used to create the initial snapshot.
  ///
394
  /// Providing this value (presumably obtained synchronously somehow when the
395
  /// [Stream] was created) ensures that the first frame will show useful data.
396 397 398 399 400
  /// Otherwise, the first frame will be built with the value null, regardless
  /// of whether a value is available on the stream: since streams are
  /// asynchronous, no events from the stream can be obtained before the initial
  /// build.
  final T initialData;
401

402
  @override
403
  AsyncSnapshot<T> initial() => AsyncSnapshot<T>.withData(ConnectionState.none, initialData);
404 405 406 407 408 409

  @override
  AsyncSnapshot<T> afterConnected(AsyncSnapshot<T> current) => current.inState(ConnectionState.waiting);

  @override
  AsyncSnapshot<T> afterData(AsyncSnapshot<T> current, T data) {
410
    return AsyncSnapshot<T>.withData(ConnectionState.active, data);
411 412 413 414
  }

  @override
  AsyncSnapshot<T> afterError(AsyncSnapshot<T> current, Object error) {
415
    return AsyncSnapshot<T>.withError(ConnectionState.active, error);
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
  }

  @override
  AsyncSnapshot<T> afterDone(AsyncSnapshot<T> current) => current.inState(ConnectionState.done);

  @override
  AsyncSnapshot<T> afterDisconnected(AsyncSnapshot<T> current) => current.inState(ConnectionState.none);

  @override
  Widget build(BuildContext context, AsyncSnapshot<T> currentSummary) => builder(context, currentSummary);
}

/// Widget that builds itself based on the latest snapshot of interaction with
/// a [Future].
///
431 432 433 434 435 436 437 438 439 440
/// The [future] must have been obtained earlier, e.g. during [State.initState],
/// [State.didUpdateConfig], or [State.didChangeDependencies]. It must not be
/// created during the [State.build] or [StatelessWidget.build] method call when
/// constructing the [FutureBuilder]. If the [future] is created at the same
/// time as the [FutureBuilder], then every time the [FutureBuilder]'s parent is
/// rebuilt, the asynchronous task will be restarted.
///
/// A general guideline is to assume that every `build` method could get called
/// every frame, and to treat omitted calls as an optimization.
///
441 442
/// {@youtube 560 315 https://www.youtube.com/watch?v=ek8ZPdWj4Qo}
///
443 444
/// ## Timing
///
445 446
/// Widget rebuilding is scheduled by the completion of the future, using
/// [State.setState], but is otherwise decoupled from the timing of the future.
447
/// The [builder] callback is called at the discretion of the Flutter pipeline, and
448 449 450
/// will thus receive a timing-dependent sub-sequence of the snapshots that
/// represent the interaction with the future.
///
451 452 453 454 455 456 457
/// A side-effect of this is that providing a new but already-completed future
/// to a [FutureBuilder] will result in a single frame in the
/// [ConnectionState.waiting] state. This is because there is no way to
/// synchronously determine that a [Future] has already completed.
///
/// ## Builder contract
///
458 459 460
/// For a future that completes successfully with data, assuming [initialData]
/// is null, the [builder] will be called with either both or only the latter of
/// the following snapshots:
461
///
462 463
/// * `new AsyncSnapshot<String>.withData(ConnectionState.waiting, null)`
/// * `new AsyncSnapshot<String>.withData(ConnectionState.done, 'some data')`
464
///
465 466
/// If that same future instead completed with an error, the [builder] would be
/// called with either both or only the latter of:
467
///
468 469 470 471 472 473 474
/// * `new AsyncSnapshot<String>.withData(ConnectionState.waiting, null)`
/// * `new AsyncSnapshot<String>.withError(ConnectionState.done, 'some error')`
///
/// The initial snapshot data can be controlled by specifying [initialData]. You
/// would use this facility to ensure that if the [builder] is invoked before
/// the future completes, the snapshot carries data of your choice rather than
/// the default null value.
475
///
476 477 478 479 480 481
/// The data and error fields of the snapshot change only as the connection
/// state field transitions from `waiting` to `done`, and they will be retained
/// when changing the [FutureBuilder] configuration to another future. If the
/// old future has already completed successfully with data as above, changing
/// configuration to a new future results in snapshot pairs of the form:
///
482 483
/// * `new AsyncSnapshot<String>.withData(ConnectionState.none, 'data of first future')`
/// * `new AsyncSnapshot<String>.withData(ConnectionState.waiting, 'data of second future')`
484 485
///
/// In general, the latter will be produced only when the new future is
486
/// non-null, and the former only when the old future is non-null.
487 488 489 490
///
/// A [FutureBuilder] behaves identically to a [StreamBuilder] configured with
/// `future?.asStream()`, except that snapshots with `ConnectionState.active`
/// may appear for the latter, depending on how the stream is implemented.
491
///
492 493 494
/// {@animation 200 150 https://flutter.github.io/assets-for-api-docs/assets/widgets/future_builder.mp4}
///
/// {@animation 200 150 https://flutter.github.io/assets-for-api-docs/assets/widgets/future_builder_error.mp4}
495
///
496 497 498 499 500 501 502
/// {@tool snippet --template=stateful_widget_material}
///
/// This sample shows a [FutureBuilder] that displays a loading spinner while it
/// loads data. It displays a success icon and text if the [Future] completes
/// with a result, or an error icon and text if the [Future] completes with an
/// error. Assume the `_calculation` field is set by pressing a button elsewhere
/// in the UI.
503 504
///
/// ```dart
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
/// Future<String> _calculation = Future<String>.delayed(
///   Duration(seconds: 2),
///   () => 'Data Loaded',
/// );
///
/// Widget build(BuildContext context) {
///   return FutureBuilder<String>(
///     future: _calculation, // a previously-obtained Future<String> or null
///     builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
///       List<Widget> children;
///
///       if (snapshot.hasData) {
///         children = <Widget>[
///           Icon(
///             Icons.check_circle_outline,
///             color: Colors.green,
///             size: 60,
///           ),
///           Padding(
///             padding: const EdgeInsets.only(top: 16),
///             child: Text('Result: ${snapshot.data}'),
///           )
///         ];
///       } else if (snapshot.hasError) {
///         children = <Widget>[
///           Icon(
///             Icons.error_outline,
///             color: Colors.red,
///             size: 60,
///           ),
///           Padding(
///             padding: const EdgeInsets.only(top: 16),
///             child: Text('Error: ${snapshot.error}'),
///           )
///         ];
///       } else {
///         children = <Widget>[
///           SizedBox(
///             child: CircularProgressIndicator(),
///             width: 60,
///             height: 60,
///           ),
///           const Padding(
///             padding: EdgeInsets.only(top: 16),
///             child: Text('Awaiting result...'),
///           )
///         ];
///       }
///       return Center(
///         child: Column(
///           mainAxisAlignment: MainAxisAlignment.center,
///           crossAxisAlignment: CrossAxisAlignment.center,
///           children: children,
///         ),
///       );
///     },
///   );
/// }
563
/// ```
564
/// {@end-tool}
565
// TODO(ianh): remove unreachable code above once https://github.com/dart-lang/linter/issues/1141 is fixed
566
class FutureBuilder<T> extends StatefulWidget {
567 568 569
  /// Creates a widget that builds itself based on the latest snapshot of
  /// interaction with a [Future].
  ///
570
  /// The [builder] must not be null.
571
  const FutureBuilder({
572 573
    Key key,
    this.future,
574
    this.initialData,
575
    @required this.builder,
576 577
  }) : assert(builder != null),
       super(key: key);
578 579

  /// The asynchronous computation to which this builder is currently connected,
580
  /// possibly null.
581 582
  ///
  /// If no future has yet completed, including in the case where [future] is
583
  /// null, the data provided to the [builder] will be set to [initialData].
584 585
  final Future<T> future;

586 587 588 589 590 591
  /// The build strategy currently used by this builder.
  ///
  /// The builder is provided with an [AsyncSnapshot] object whose
  /// [AsyncSnapshot.connectionState] property will be one of the following
  /// values:
  ///
592 593 594
  ///  * [ConnectionState.none]: [future] is null. The [AsyncSnapshot.data] will
  ///    be set to [initialData], unless a future has previously completed, in
  ///    which case the previous result persists.
595
  ///
596 597 598 599
  ///  * [ConnectionState.waiting]: [future] is not null, but has not yet
  ///    completed. The [AsyncSnapshot.data] will be set to [initialData],
  ///    unless a future has previously completed, in which case the previous
  ///    result persists.
600 601 602 603 604 605
  ///
  ///  * [ConnectionState.done]: [future] is not null, and has completed. If the
  ///    future completed successfully, the [AsyncSnapshot.data] will be set to
  ///    the value to which the future completed. If it completed with an error,
  ///    [AsyncSnapshot.hasError] will be true and [AsyncSnapshot.error] will be
  ///    set to the error object.
606 607
  final AsyncWidgetBuilder<T> builder;

608 609 610
  /// The data that will be used to create the snapshots provided until a
  /// non-null [future] has completed.
  ///
611 612 613
  /// If the future completes with an error, the data in the [AsyncSnapshot]
  /// provided to the [builder] will become null, regardless of [initialData].
  /// (The error itself will be available in [AsyncSnapshot.error], and
614
  /// [AsyncSnapshot.hasError] will be true.)
615 616
  final T initialData;

617
  @override
618
  State<FutureBuilder<T>> createState() => _FutureBuilderState<T>();
619 620 621 622 623 624 625 626
}

/// State for [FutureBuilder].
class _FutureBuilderState<T> extends State<FutureBuilder<T>> {
  /// An object that identifies the currently active callbacks. Used to avoid
  /// calling setState from stale callbacks, e.g. after disposal of this state,
  /// or after widget reconfiguration to a new Future.
  Object _activeCallbackIdentity;
627
  AsyncSnapshot<T> _snapshot;
628 629 630 631

  @override
  void initState() {
    super.initState();
632
    _snapshot = AsyncSnapshot<T>.withData(ConnectionState.none, widget.initialData);
633 634 635 636
    _subscribe();
  }

  @override
637
  void didUpdateWidget(FutureBuilder<T> oldWidget) {
638
    super.didUpdateWidget(oldWidget);
639
    if (oldWidget.future != widget.future) {
640 641 642 643 644 645 646 647 648
      if (_activeCallbackIdentity != null) {
        _unsubscribe();
        _snapshot = _snapshot.inState(ConnectionState.none);
      }
      _subscribe();
    }
  }

  @override
649
  Widget build(BuildContext context) => widget.builder(context, _snapshot);
650 651 652 653 654 655 656 657

  @override
  void dispose() {
    _unsubscribe();
    super.dispose();
  }

  void _subscribe() {
658
    if (widget.future != null) {
659
      final Object callbackIdentity = Object();
660
      _activeCallbackIdentity = callbackIdentity;
661
      widget.future.then<void>((T data) {
662 663
        if (_activeCallbackIdentity == callbackIdentity) {
          setState(() {
664
            _snapshot = AsyncSnapshot<T>.withData(ConnectionState.done, data);
665 666 667 668 669
          });
        }
      }, onError: (Object error) {
        if (_activeCallbackIdentity == callbackIdentity) {
          setState(() {
670
            _snapshot = AsyncSnapshot<T>.withError(ConnectionState.done, error);
671 672 673 674 675 676 677 678 679 680 681
          });
        }
      });
      _snapshot = _snapshot.inState(ConnectionState.waiting);
    }
  }

  void _unsubscribe() {
    _activeCallbackIdentity = null;
  }
}