Flutter从入门到入土(三)网络请求Dio

1、网络请求

 1   Dio _dio = new Dio();
 2 
 3   Future getInformationJson(User user) async {
 4 
 5     var url = 'http://xxx/xxx/xxx?username=' + user._username +
 6         '&password=' + user._password;
 7 
 8     Response response = await _dio.get(url);
 9     if (response.statusCode == HttpStatus.ok) {
10       var data = jsonDecode(response.toString());  //JSON数据的解析
11       try{
12         data['payload']['scores'].forEach((v) {
13 //          print(v['className']);
14           Scores score = new Scores(
15               v['term'], v['className'], v['credit'].toString(), v['score'],
16               v['gpa'].toString());
17           user._scores.add(score);
18         });
19 
20         user._avggpa = data['payload']['gpa'].toString();
21         user._avgscore = data['payload']['avg'].toString();
22         user._size = data['payload']['size'].toString();
23       }catch(e){
24         print(e);
25       }
26     }
27     return user;
28   }

 

2、异步请求(在执行界面渲染的类当中)

1   void initState() {
2     super.initState();
3     user = new User();
4 
5     information.getInformationJson(user).then((val){
6       user = val;
7       build(context);
8     });
9   }

 

使用setState(() {});

 1   @override
 2   Widget build(BuildContext context){
 3     // TODO: implement build
 4 
 5     if(user._scores == null || user._scores.length == 0){
 6       return loadingWidget();
 7     }else{
 8       print('main');
 9       setState(() {});
10       return mainWidget();
11     }
12   }

当user获得到数据后就会重新渲染页面(loadingWidget ==> mainWidget)

 

posted @ 2020-05-20 23:38  北冥雪  阅读(572)  评论(0编辑  收藏  举报