![fe42817a3c433cd9cd5275b6e40a168e.png](https://img-blog.csdnimg.cn/img_convert/fe42817a3c433cd9cd5275b6e40a168e.png)
背景
- 开发flutter-ui过程中,遇到了全局弹窗问题
- 友好的交互界面,能够产生更好的用户体验,比如查询接口较久或需要耗时处理程序时,给个loading效果。
- flutter组件中showDialog弹窗组件,能满足弹窗需求,但使用过程可能不太顺手。
将从以下几点来分析与实现接口请求前的弹窗效果 - showDialog介绍 - 实现简单弹窗 - 接入dio package - 弹窗关键点分析 - 实现全局存储context - 实现dio请求时loading - 并发请求时loading处理
本文相关链接 - flutter-ui - dio - provide
准备
- 新建项目flutter create xxx (有项目就用自己项目,影响的地方不大)
- pubspec.yaml增加dio依赖包
dependencies:
flutter:
sdk: flutter
dio: ^2.1.0 # dio依赖包 2019/03/30
- 创建http文件夹与http/index.dart, http/loading.dart文件
lib
|--http #文件
|--index.dart # dio
|--loading.dart #loading
|--main.dart #入口
showDialog介绍
showDialog{
@required BuildContext context,
bool barrierDismissible = true,
@Deprecated(
'Instead of using the "child" argument, return the child from a closure '
'provided to the "builder" argument. This will ensure that the BuildContext '
'is appropriate for widgets built in the dialog.'
) Widget child,
WidgetBuilder builder,
}
- builder:创建弹窗的组件,这些可以创建需要的交互内容
- context:上下文,这里只要打通了,就能实现全局。这是关键
查看showDialog源码,调用顺序是
showDialog -> showGeneralDialog -> Navigator.of(context, rootNavigator: true).push() context作为参数,作用是提供给了Navigator.of(context, rootNavigator: true).push使用
- showGeneralDialog的注释内容,介绍了关闭弹窗的重点
/// The dialog route created by this method is pushed to the root navigator.
/// If the application has multiple [Navigator] objects, it may be necessary to
/// call `Navigator.of(context, rootNavigator: true).pop(result)` to close the
/// dialog rather than just `Navigator.pop(context, result)`.
///
/// See also:
///
/// * [showDialog], which displays a Material-style dialog.
/// * [showCupertinoDialog], which displays an iOS-style dialog