Dart中的异步请求和等待和ES6中的方法很像,直接使用async...await就可以实现。
核心代码:
_navigateToAddress(BuildContext context) async{ //async是启用异步方法 final result = await Navigator.push(//等待
context,
MaterialPageRoute(builder: (context)=> Address())
); Scaffold.of(context).showSnackBar(SnackBar(content:Text('$result')));
}
示例:
import 'package:flutter/material.dart'; void main(){
runApp(MaterialApp(
title:'页面跳转返回数据',
home:FirstPage()
));
} class FirstPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar:AppBar(title:Text("商品列表")),
body:Center(
child: RouteButton(),
)
);
}
} //跳转的Button
class RouteButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
return RaisedButton(
onPressed:(){
_navigateToAddress(context);
},
child: Text('选择地址'),
);
} _navigateToAddress(BuildContext context) async{ //async是启用异步方法 final result = await Navigator.push(//等待
context,
MaterialPageRoute(builder: (context)=> Address())
); Scaffold.of(context).showSnackBar(SnackBar(content:Text('$result')));
}
} class Address extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar:AppBar(
title:Text('地址列表')
),
body:Center(
child:Column(
children: <Widget>[
RaisedButton(
child: Text('地址一'),
onPressed: (){
Navigator.pop(context,'地址一:北京');
},
) ,
RaisedButton(
child: Text('地址二'),
onPressed: (){
Navigator.pop(context,'地址二:上海');
},
) ,
],
)
) ,
);
}
}