美文网首页
从零开始用flutter写一个完整应用⑸:网络请求

从零开始用flutter写一个完整应用⑸:网络请求

作者: 逃离_102 | 来源:发表于2022-06-16 22:57 被阅读0次

说明

对一个移动端应用而言,网络请求是最基础功能之一,数据基本都是通过网络请求来获取。这2种是最常用的2种网络请求方式,所以我把它们归一起了。网络请求一般有2种一种是用原生的httpclient; 一种是第3方库http库或者dio库。

1,原生httpclient

导入dart:io,然后如下进行就可以了

import 'dart:io';

Future<Data> dioData(int page,int size) async {
  final request = await HttpClient().getUrl(Uri.parse("https://api.apiopen.top/api/getHaoKanVideo?page=$page&size=$size"));
  final response = await request.close();
  if (response.statusCode == HttpStatus.ok) {
    var json = await response.transform(utf8.decoder).join();
    return Data.fromJson(jsonDecode(json));
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load Data');
  }
}

当然网络请求少不了json解析,下面还会用到就一起放这了,这个属于复杂解析,基本满足所用情况了

// {
//   "code": 200,
//   "message": "成功!",
//   "result": {
//     "total": 11860,
//     "list": [
//       {
//       "id": 7525,
//       "title": "敢直接叫向华强要人,周润发当配角,给张学友做个表情包",
//       "userName": "也毁灭另一些人",
//       "userPic": "https://pic.rmb.bdstatic.com/bjh/user/00f938d6a2615985a2fe68b40252d319.jpeg?x-bce-process=image/resize,m_lfit,w_200,h_200&autime=33634",
//       "coverUrl": "https://f7.baidu.com/it/u=4107050099,3096145322&fm=222&app=108&f=JPEG@s_2,w_681,h_381,q_100",
//       "playUrl": "http://vd2.bdstatic.com/mda-nc5e6rphet3kr6td/cae_h264_delogo/1646561464607182321/mda-nc5e6rphet3kr6td.mp4",
//       "duration": "01:19"
//       },
//       {
//       "id": 10948,
//       "title": "吕秀才倒霉的一天",
//       "userName": "影视小滔",
//       "userPic": "https://pic.rmb.bdstatic.com/bjh/user/ae482e23dfca594081b51d558d8367ac.jpeg?x-bce-process=image/resize,m_lfit,w_200,h_200&autime=37424",
//       "coverUrl": "https://f7.baidu.com/it/u=3822864426,1054969009&fm=222&app=108&f=JPEG@s_2,w_681,h_381,q_100",
//       "playUrl": "http://vd3.bdstatic.com/mda-ndg2vcdujbewdd9m/cae_h264_delogo/1650161723467982957/mda-ndg2vcdujbewdd9m.mp4",
//       "duration": "05:21"
//       }
//     ]
//   }
// }
class Data {
  final int code;
  final String message;
  final Result result;

  const Data({
    required this.code,
    required this.message,
    required this.result,
  });

  factory Data.fromJson(Map<String, dynamic> json) {
    return Data(
      code: json['code'],
      message: json['message'],
      result: Result.fromJson(json['result']),
    );
  }
}

class Result {
  final int total;
  final List<ItemBean> list;

  const Result({
    required this.total,
    required this.list,
  });

  factory Result.fromJson(Map<String, dynamic> json) {
    var listT = json['list'] as List;
    List<ItemBean> lists = listT.map((i) => ItemBean.fromJson(i)).toList();
    return Result(
      total: json['total'],
      list: lists,
    );
  }

}

class ItemBean {
  final int id;
  final String title;
  final String userName;
  final String userPic;
  final String coverUrl;
  final String playUrl;
  final String duration;

  const ItemBean({
    required this.id,
    required this.title,
    required this.userName,
    required this.userPic,
    required this.coverUrl,
    required this.playUrl,
    required this.duration,
  });

  factory ItemBean.fromJson(Map<String, dynamic> json) {
    return ItemBean(
      id: json['id'],
      title: json['title'],
      userName: json['userName'],
      userPic: json['userPic'],
      coverUrl: json['coverUrl'],
      playUrl: json['playUrl'],
      duration: json['duration'],
    );
  }
}

2,用http第3方库

加入依赖http: ^0.13.3;
导入import 'package:http/http.dart' as http;
分get,post,根据需求选择

Future<Data> fetchData(int page,int size) async {
  final response = await http.get(Uri.parse('https://api.apiopen.top/api/getHaoKanVideo?page=$page&size=$size'));

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return Data.fromJson(jsonDecode(response.body));
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load Data');
  }
}

Future<Data> fetchPostData(int page,int size) async {
    //头部
    var headers = Map<String, String>();
    headers["Content-Type"] = "application/json";
    //参数
    Map params = {'page': '$page','size':'$size'};
    // 嵌套两层都可以,但是具体哪个好还有待确认????
    var jsonParams = utf8.encode(json.encode(params));
    // var jsonParams = json.encode(params);
    var httpClient = http.Client();
    var uri = Uri.parse("https://api.apiopen.top/api/getHaoKanVideo");
    final response = await httpClient.post(uri, body: jsonParams, headers: headers);

    if (response.statusCode == 200) {
        return Data.fromJson(jsonDecode(response.body));
    } else {
        throw Exception('Failed to load Data');
    }
}

3,用dio第3方库

加入依赖dio : ^4.0.6;
导入import 'package:dio/dio.dart';
可get,post,下载,断点续传等功能,功能很强大,可根据需求,再仔细学习

Future<Data> dioData(int page,int size) async {
  Dio dio = Dio();
  final response = await dio.get("https://api.apiopen.top/api/getHaoKanVideo?page=$page&size=$size");
  if (response.statusCode == 200) {
    return Data.fromJson(response.data);
  } else {
    throw Exception('Failed to load Data');
  }
}

Future<Data> dioPostData(int page,int size) async {
  Dio dio = Dio();
  //参数
  Map params = {'page': '$page','size':'$size'};
  final response = await dio.post("https://api.apiopen.top/api/getHaoKanVideo",data:params);
  if (response.statusCode == 200) {
    return Data.fromJson(response.data);
  } else {
    throw Exception('Failed to load Data');
  }
}

demo

上主要是讲解了一些基本的用法,更详细的可参照demo
demo地址:https://github.com/liuyewu101/flutter_demo

相关文章

网友评论

      本文标题:从零开始用flutter写一个完整应用⑸:网络请求

      本文链接:https://www.haomeiwen.com/subject/innlmrtx.html