Flutter知识点: 网络请求

App几乎都离不开与服务器的交互,介绍Flutter中的网络请求以及解析。

Flutter原生网络请求

var httpClient = new HttpClient();
  var url = Constant.baseUrl + 'Android/1/1';

  _loadData() async {
    try {
      var request = await httpClient.getUrl(Uri.parse(url));
      var response = await request.close();
      if (response.statusCode == HttpStatus.OK) {
        _result = await response.transform(UTF8.decoder).join();
        _decodeJson(_result, false);
      } else {
        _result = 'error code : ${response.statusCode}';
      }
    } catch (exception) {
      _result = '网络异常';
    }

    // If the widget was removed from the tree while the message was in flight,
    // we want to discard the reply rather than calling setState to update our
    // non-existent appearance.
    if (!mounted) return;

    setState(() {});
  }

使用第三方库http

  var client = new http.Client();

  _loadDataByHttp() async {
    try {
      http.Response response = await client.get(url);
      if (response.statusCode == HttpStatus.OK) {
        if (response.statusCode == HttpStatus.OK) {
          _result = response.body.toString();
          _decodeJson(_result, false);
        } else {
          _result = 'error code : ${response.statusCode}';
        }
      } else {
        _result = 'error code : ${response.statusCode}';
      }
    } catch (exception) {
      _result = '网络异常';
    }

    setState(() {});
  }

使用第三方库dio

 Dio dio = new Dio();

  _loadDataByDio() async {
    try {
      Response response = await dio.get(url);
      if (response.statusCode == HttpStatus.OK) {
        _result = response.data.toString();
        _decodeJson(response.data, true);
      } else {
        _result = 'error code : ${response.statusCode}';
      }
    } catch (exception) {
      print('exc:$exception');
      _result = '网络异常';
    }

    setState(() {});
  }

数据解析

  _decodeJson(var body, bool isDio) {
    var json;

    if (isDio) {
      //如果是Dio则不需要jsonDecode
      json = body;
    } else {
      json = jsonDecode(body);
    }

    List flModels = json['results'];

    List list = flModels.map((model) {
      return new AIModel.fromJson(model);
    }).toList();

    for (AIModel model in list) {
      _decodeResult =
          '作者:${model.who}\n描述:${model.desc}\n地址:${model.url}\n时间:${DateTime.parse(
          model.publishedAt)}';
    }

    setState(() {});
  }

效果展示

Flutter知识点: 网络请求_第1张图片
8.jpeg
Flutter知识点: 网络请求_第2张图片
3.jpeg

本文针对3种方式只做了简单的数据请求,如果在实际项目中建议您使用dio 来发起网络请求,它是一个强大易用的dart http请求库,支持Restful API、FormData、拦截器、请求取消、Cookie管理、文件上传/下载……详情请查看github dio。

已有项目集成到Flutter代码已经上传到我的GITHUB

知乎日报Flutter版代码已经上传到我的GITHUB

基础学习过程中的代码都放在GITHUB

每天学一点,学到Flutter发布正式版!

你可能感兴趣的:(Flutter知识点: 网络请求)