在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'),
},
);
}