如何解决Flutter StreamBuilder 具有初始数据和空感知
我在使用新的空感知运算符理解 StreamBuilder 时遇到了一些问题。
作为一个学习项目,我正在使用 BloC 模式实现登录流程。对于我的电子邮件登录表单,我创建了一个模型类,我可以通过 StreamBuilder 访问它。如果不使用initialData,那么snapshot.data 可以为null 是完全合理的。但是,将 initialData 设置为预定义的空模型,snapshot.data 永远不会为空,对吗?这是我的代码片段:
@override
Widget build(BuildContext context) {
return StreamBuilder<EmailSignInModel>(
stream: widget.bloc.modelStream,initialData: EmailSignInModel(),builder: (context,snapshot) {
final EmailSignInModel model = snapshot.data;
return Padding(
padding: const EdgeInsets.all(16.0),child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,mainAxisSize: MainAxisSize.min,children: _buildChildren(),),);
});
}
编译器警告我,snapshot.data 是 snapshot.data ?? EmailSignModel()
解决这个问题,但这对 initialData 来说是多余的,对吗?
处理这种情况并注意 Dart 的 null 感知的正确方法是什么?
解决方法
深入研究源代码,我发现了以下内容:
https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/widgets/async.dart
/// 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;
/// Returns latest data received,failing if there is no data.
///
/// Throws [error],if [hasError]. Throws [StateError],if neither [hasData]
/// nor [hasError].
T get requireData {
if (hasData)
return data!;
if (hasError)
throw error!;
throw StateError('Snapshot has neither data nor error');
}
AsyncSnapshot
实际上有一个 requireData
getter,它会确保非空或者会抛出错误。所以只需将 snapshot.data
替换为 snapshot.requireData
这仍然需要一些手动工作,其中 initialData
和 requireData
的使用需要保持同步。您也可以只使用 snapshot.data!
,它的作用基本相同。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。