Flutter Future 异步处理,类似登录、上传文件带进度条效果显示处理方法

        在Flutter 登录、上传文件等类似业务中,可以有带进度条的效果显示,下图中,首先通过 _showDialog()显示带进度条的对话框,在异步完成后,通过Navigator.of(context).pop()退出进度条,跳转到其他的页面或对结果进一步处理。

import 'package:flutter/material.dart';

void main() {
  runApp(Demo());
}

class Demo extends StatelessWidget {
  //const Demo({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(body: MyApp()),
    );
  }
}

class MyApp extends StatefulWidget {
  //const MyApp({Key key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        width:100,
        height:100,
        color:Colors.red,
        child: TextButton(
          onPressed: () {
            _showDialog("abc");
            _getUserInfo()
                .then((value) => {
                  print(value),
                   Navigator.of(context).pop()});
          },
          child: Text('text'),
        ),
      ),
    );
  }

  void _showDialog() {
    showDialog(
      barrierDismissible: false,
      context: context,
      builder: (context) => AlertDialog(
        title: Text('登录中...'),
        content: Center(
          heightFactor: 0.4,
          child: CircularProgressIndicator(),
        ),
      ),
    );
  }

  Future _getUserInfo() async {
    await Future.delayed(Duration(milliseconds: 3000));

    return '1';
  }
}

Flutter 异步处理机制 

Future testFuture() async {
  print('testFuture');
  throw AssertionError('assert error2');
  //await Future.delayed(Duration(milliseconds: 3000));
}

//调用处
void main() {
  testFuture().then(
    (value) {
      print('object...');
    },
    onError: (_) {
      //print(_.toString());
      print('onError');
    },
  ).whenComplete(
    () => {
      print('Complete'),
    },
  );
}

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

computerclass

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值