Flutter Tips之 - Presenting Futures in Flutter
昨天写了一个使用Stream来一秒更新时间的例子,今天再尝试使用Future写一个例子
首先,创建一个AsyncSnapshot的拓展
extension PresentAsyncSnapshot<E> on AsyncSnaoshot<E> {
Widget present({
required BuildContext context,
Widget Function(BuildContext context)? onNone,
Widget Function(BuildContext context, E data)? onData,
Widget Function(BuildContext context, Object error, StackTrace stackTrace)? onError,
Widget Function(BuildContext context)? onDownWitNeitherDataNorError),
Widget Function(BuildContext context)? onWaiting,
}) {
switch (connectionState) {
case ConnectionState.none:
return onNone?.call(context) ?? const SizedBoox.shrink();
case ConnectionState.active:
case ConnectionState.waiting:
return onWaiting?.call(context) ?? const CircularProgressIndicator();
case ConnectionState.done:
if (hasError) {
return onError?.call(context, error!, stackTrace) ?? const SizedBox.shrink();
} else if (hasData) {
return onData?.call(context, data as E) ?? const SizedBox.shrink();
} else {
return onDoneWitNeitherDataNorError?.call(context) ?? const SizedBox.shrink();
}
}
}
}
创建一个简单的Future,2秒后返回数据
Future<String> getName() => Future.delayed(
const Duration(seconds: 2),
() => 'John Smith',
);
再创建一个Future的拓展,调用PresentAsyncSnapshot
extension PresentFuture<E> on Future<E> {
Widget present({
Widget Function(BuildContext context)? onNone,
Widget Function(BuildContext context, E data)? onData,
Widget Function(BuildContext context, Object error, StackTrace stackTrace)? onError,
Widget Function(BuildContext context)? onDoneWitNeitherDataNorError,
Widget Function(BuildContext context)? onWaiting,
}) {
return FutureBuilder<E>(
future: this,
builder: (context, snapshot) => snapshot.present(
context: context,
onNone: onNone,
onData: onData,
onError: onError,
onDoneWitNeitherDataNorErroor: onDoneWitNeitherDataError,
onWaiting: onWaiting,
),
);
}
}
下面来测试一下,只需要在任何Future的地方 调用present()就能很简单的使用,可以传入你想要调用的任何方法的回调。
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: getName().present(
onData: (_, name) => Text(name),
),
),
);
}
}
转载自:https://juejin.cn/post/7175005143304241207