【Flutter】FutureBuilder 异步编程 ( FutureBuilder 构造方法 | AsyncSnapshot 异步计算 )

简介: 【Flutter】FutureBuilder 异步编程 ( FutureBuilder 构造方法 | AsyncSnapshot 异步计算 )

文章目录

一、FutureBuilder 简介

二、FutureBuilder 构造方法

三、AsyncSnapshot 异步计算






一、FutureBuilder 简介


FutureBuilder 将 异步操作 与 异步 UI 更新 结合在一起 ; 它可以将 异步操作 的结果 , 异步的 更新到 UI 界面中 ;


异步操作结果 : 网络请求 , 数据库读取 , 等耗时操作 得到的结果 ;






二、FutureBuilder 构造方法


FutureBuilder 构造方法如下 :


/// Creates a widget that builds itself based on the latest snapshot of
/// interaction with a [Future].
///
/// The [builder] must not be null.
const FutureBuilder({
  Key? key,
  this.future,
  this.initialData,
  required this.builder,
}) : assert(builder != null),
     super(key: key);
FutureBuilder({Key key, Future<T> future, T initialData, @required AsyncWidgetBuilder<T> builder })



FutureBuilder 构造方法参数解析 :


Future<T> future : 与异步操作相关的异步计算 ;

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


T initialData : 异步计算完成前的初始化数据 ;

/// The data that will be used to create the snapshots provided until a
  /// non-null [future] has completed.
  ///
  /// 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
  /// [AsyncSnapshot.hasError] will be true.)
  final T? initialData;


@required AsyncWidgetBuilder<T> builder : AsyncWidgetBuilder 类型的回调函数 , 这是基于异步交互构建 Widget 的函数 ;

/// Signature for strategies that build widgets based on asynchronous
/// interaction.
///
/// See also:
///
///  * [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].
typedef AsyncWidgetBuilder<T> = Widget Function(BuildContext context, AsyncSnapshot<T> snapshot);






三、AsyncSnapshot 异步计算


AsyncWidgetBuilder<T> 回调函数的实际类型是 Widget Function(BuildContext context, AsyncSnapshot<T> snapshot) , 接收两个参数 BuildContext context 和 AsyncSnapshot<T> snapshot , 返回值是 Widget 组件 ;


AsyncSnapshot<T> snapshot 参数中包含有异步计算的信息 ;


class AsyncSnapshot<T> {
  /// Creates an [AsyncSnapshot] with the specified [connectionState],
  /// and optionally either [data] or [error] with an optional [stackTrace]
  /// (but not both data and error).
  const AsyncSnapshot._(this.connectionState, this.data, this.error, this.stackTrace)
    : assert(connectionState != null),
      assert(!(data != null && error != null)),
      assert(stackTrace == null || error != null);
  /// Current state of connection to the asynchronous computation.
  final ConnectionState connectionState;
  /// The latest data received by the asynchronous computation.
  ///
  /// If this is non-null, [hasData] will be true.
  ///
  /// If [error] is not null, this will be null. See [hasError].
  ///
  /// 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;
  /// 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.
  final Object? 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;
  /// Returns whether this snapshot contains a non-null [error] value.
  ///
  /// This is always true if the asynchronous computation's last result was
  /// failure.
  bool get hasError => error != null;
}


AsyncSnapshot<T> snapshot 中的 ConnectionState connectionState 是连接状态 , 是个枚举值 , 有四种取值 :


none

waiting

active

done

/// The state of connection to an asynchronous computation.
///
/// The usual flow of state is as follows:
///
/// 1. [none], maybe with some initial data.
/// 2. [waiting], indicating that the asynchronous operation has begun,
///    typically with the data being null.
/// 3. [active], with data being non-null, and possible changing over time.
/// 4. [done], with data being non-null.
///
/// See also:
///
///  * [AsyncSnapshot], which augments a connection state with information
///    received from the asynchronous computation.
enum ConnectionState {
  /// Not currently connected to any asynchronous computation.
  ///
  /// For example, a [FutureBuilder] whose [FutureBuilder.future] is null.
  none,
  /// Connected to an asynchronous computation and awaiting interaction.
  waiting,
  /// Connected to an active asynchronous computation.
  ///
  /// For example, a [Stream] that has returned at least one value, but is not
  /// yet done.
  active,
  /// Connected to a terminated asynchronous computation.
  done,
}


final T? data 是异步计算接收的最新数据 ;


Object? error 是异步计算接收的错误对象 ;


AsyncSnapshot<T> snapshot 中还有 hasData 和 hasError 两个属性 , hasData 用于检查该对象是否包含非空数据值 , hasError 用于检查是否包含错误值 ;


/// 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;
  /// Returns whether this snapshot contains a non-null [error] value.
  ///
  /// This is always true if the asynchronous computation's last result was
  /// failure.
  bool get hasError => error != null;


目录
相关文章
|
11月前
|
缓存 监控 前端开发
优化 Flutter 应用启动速度的策略,涵盖理解启动过程、资源加载优化、减少初始化工作、界面布局优化、异步初始化、预加载关键数据、性能监控与分析等方面
本文探讨了优化 Flutter 应用启动速度的策略,涵盖理解启动过程、资源加载优化、减少初始化工作、界面布局优化、异步初始化、预加载关键数据、性能监控与分析等方面,并通过案例分析展示了具体措施和效果,强调了持续优化的重要性及未来优化方向。
445 10
|
Dart 前端开发 JavaScript
Flutter&Dart-异步编程Future、Stream极速入门
Flutter&Dart-异步编程Future、Stream极速入门
208 4
Flutter&Dart-异步编程Future、Stream极速入门
|
12月前
|
机器学习/深度学习 开发框架 Dart
Flutter asynchronous 异步编程技巧
本文深入探讨了Flutter中的异步编程技巧,包括Future、Microtask及并发处理的最佳实践。文章详细讲解了Future.wait、FutureBuilder和Microtask的应用,帮助开发者提升应用性能。通过实例演示了如何利用Future.wait实现并发执行,FutureBuilder简化UI构建,以及Microtask的高优先级执行特性。适合希望优化Flutter应用异步性能的开发者阅读。
206 0
|
Dart
flutter 之 Dart 异步编程【详解】
flutter 之 Dart 异步编程【详解】
194 0
|
Dart 前端开发 UED
【Flutter前端技术开发专栏】深入理解Flutter中的流(Streams)和异步编程
【4月更文挑战第30天】探索Flutter的异步编程与流:了解异步编程在提升响应性和避免阻塞中的作用,掌握Stream、StreamController和StreamSubscription核心概念。通过实践案例学习如何使用流处理网络请求,提升应用性能。参考Dart和Flutter官方文档,深入理解并运用异步模式,如回调、async/await和Futures,构建更佳用户体验的Flutter应用。
223 0
【Flutter前端技术开发专栏】深入理解Flutter中的流(Streams)和异步编程
|
Dart 前端开发 API
【Flutter前端技术开发专栏】Flutter中的异步编程与Future/async/await
【4月更文挑战第30天】本文探讨了Flutter中的异步编程,强调其在提高应用响应性和性能上的重要性。Flutter使用`Future`对象表示异步操作的结果,通过`.then()`和`.catchError()`处理异步任务。此外,Dart的`async/await`关键字简化了异步代码,使其更易读。理解并运用这些概念对于开发高效的Flutter应用至关重要。
143 0
【Flutter前端技术开发专栏】Flutter中的异步编程与Future/async/await
|
编解码 Dart UED
Flutter单线程异步及Isolate使用过程遇到的问题
Flutter单线程异步及Isolate使用过程遇到的问题 在Flutter中,所有的代码都运行在单线程中。这意味着如果我们的代码执行时间过长,就会导致UI线程卡顿,影响用户体验。因此,Flutter提供了一些异步机制来解决这个问题。
353 0
|
Dart 开发者
Flutter入门之Dart中的并发编程、异步和事件驱动详解
Flutter入门之Dart中的并发编程、异步和事件驱动详解 Dart是一种高效、快速、灵活且用于Web和移动应用程序开发的编程语言。在Dart中,支持并发编程、异步和事件驱动等特性,这些特性使得Dart在处理诸如网络请求、文件I/O、用户输入等方面表现出色。本文将详细介绍Dart中的这些特性。
268 0
|
Dart 前端开发 JavaScript
Flutter(二十二)——异步编程
Flutter(二十二)——异步编程
347 2
Flutter(二十二)——异步编程