记录一些我的flutter开发经验

关于异步get请求(async)

pubspec.yaml
dependencies:
dio: any
json_annotation: ^0.2.3
dev_dependencies:
build_runner: ^0.9.0
json_serializable: ^0.5.4

新建一个用于连接的类
import 'dart:convert';
import 'package:dio/dio.dart';
void getTest() async{
  Response response;
  var dio = new Dio();
  response = await dio.get("https://www.test.com/public/newhome/get/10007");
  
if (response != null) {
  var res2Json  = json.encode(response.data);
  Map<String,dynamic> map=json.decode(res2Json);
  print("你好"+map["msg"]);
}
  
}

在网上找了一个执行请求的实例

import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:io';

void main() => runApp(MyApp());

var hotMovies =
    'https://api.douban.com/v2/movie/in_theaters?apikey=0df993c66c0c636e29ecbb5344252a4a';

class MyApp extends StatelessWidget {

  var movies = '';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'HttpClient请求示例',
        theme: new ThemeData(
          primaryColor: Colors.white,
        ),
        home: new Scaffold(
          appBar: new AppBar(
            title: new Text('HttpClient请求示例'),
          ),
          body: new Column(children: <Widget>[
            new RaisedButton(
                child: new Text('获取电影列表'), onPressed: getFilmList),
            new Expanded(
              child: new Text('$movies'),
            )
          ]),
        ));
  }

 void getFilmList() async {
    try {
      HttpClient httpClient = new HttpClient();
      HttpClientRequest request = await httpClient.getUrl(Uri.parse(hotMovies));
      HttpClientResponse response = await request.close();
      var result = await response.transform(utf8.decoder).join();
      movies = result;
      print('movies'+result);
      httpClient.close();
    }catch(e){
      print('请求失败:$e');
    }
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值