昨天写了一个使用Stream来一秒更新时间的例子,今天再尝试使用Future写一个例子
首先,创建一个AsyncSnapshot的拓展
extension PresentAsyncSnapshot on AsyncSnaoshot {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 getName() => Future.delayed(const Duration(seconds: 2),() => 'John Smith',
);
再创建一个Future的拓展,调用PresentAsyncSnapshot
extension PresentFuture on Future {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(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);@overrideWidget build(BuildContext context) {return Scaffold(body: SafeArea(child: getName().present(onData: (_, name) => Text(name),),),);}
}
为大家准备了一个前端资料包。包含54本,2.57G的前端相关电子书,《前端面试宝典(附答案和解析)》,难点、重点知识视频教程(全套)。
有需要的小伙伴,可以点击下方卡片领取,无偿分享