Flutterの网络请求loading

3,772 阅读1分钟

loading本身

我封装在了一个文件里,引用时只需CommonUtil.showLoadingDialog(context);

import 'package:flutter/material.dart';
class CommonUtil {
  static Future<Null> showLoadingDialog(BuildContext context) {
    return showDialog(
        context: context,
        builder: (BuildContext context) {
          return new Material(
              color: Colors.transparent,
              child: WillPopScope(
                  onWillPop: () => new Future.value(false),
                  child: Center(
                    child: new CupertinoActivityIndicator(),
                  )));
        });
  }
}

情况1:进入新页面前的loading

使用情况:在当前页面跳转到新页面时需要当前页面通过网络请求得到的值作为跳转的依据 如果还没得到返回值前就跳转,会出错

页面1-》页面2-》页面3(渲染需要页面2的值)

页面1:跳转到下个页面之后 显示loading

 child: GestureDetector(
            onTap: () {

              CommonUtil.openPage(context, EquipmentDetails(item['id']));//路由跳转操作
              prefix0.CommonUtil.showLoadingDialog(context); //同公司别人教的,没想到还能这样
            },

页面2: 获取到数据后关闭loading

init时:
    Map<String, dynamic> map = new Map();
    map ={
      "id":widget.id
    };
//    CommonUtil.showLoadingDialog(context);
    var res = await HttpManager.netFetch(
        context, Address.deviceGet(), map, null, null,
        noTip: true);
    if (res != null) {
      if (res.result) {

          setState(() {
            _map = res.data;
          });
//以上都是获取网络数据
          Navigator.pop(context);//关闭loading

情况2:点击按钮loading

我一般是用在网络请求慢的接口,怕在请求的时候用户乱点, 比如微信验证登陆,很慢

GestureDetector(
            onTap: () async{
             Map<String, dynamic> map = new Map();
                map ={
                  "id":widget.id
                };
               CommonUtil.showLoadingDialog(context);//发起请求前弹出loading
                var res = await HttpManager.netFetch(
                    context, Address.deviceGet(), map, null, null,
                    noTip: true);
                if (res != null) {
                  if (res.result) {
            
                      setState(() {
                        _map = res.data;
                      });
            //以上都是获取网络数据
                      Navigator.pop(context);//请求后关闭loading
                        },
   

后记

情况1的时候我本来是在initState时用的loading,但是出错,说是initState before 啥的 应该是在页面渲染之前不能显示弹框吧 说不定加个mouted就能行,加个Future.delay感觉也行