请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

【重要】基于Http实现网络操作-文档和源码

网络请求是开发APP必不可少的一部分,比如获取用户订单数据,获取商品列表,提交表单等等都离不了网络请求,那么在Flutter中如何进行网络请求呢?

Flutter官方推荐我们在Flutter中用Http进行网络请求。

什么是Http?

Http 是Flutter社区开发的一个可组合的、跨平台的用于Flutter的网络请求插件。

如何用http库做get请求?

  • pubspec.yaml中引入http插件;
  • 调用http.get发送请求;
dependencies:
  http: <latest_version>
Future<http.Response> fetchPost() {
  return http.get('https://jsonplaceholder.typicode.com/posts/1');
}

http.get()返回一个包含http.ResponseFuture

  • Future:是与异步操作一起工作的核心Dart类。它用于表示未来某个时间可能会出现的可用值或错误;
  • http.Response:类包含一个成功的HTTP请求接收到的数据;

在一节会重点讲解Future的用法,如何从Future中获取服务端具体的返回数据。

如何用http库做post请求?

  • pubspec.yaml中引入http插件;
  • 调用http.post发送请求;
dependencies:
  http: <latest_version>
Future<http.Response> fetchPost() {
  return http.post('https://jsonplaceholder.typicode.com/posts/1');
}

http.post()返回一个包含http.ResponseFuture

  • Future:是与异步操作一起工作的核心Dart类。它用于表示未来某个时间可能会出现的可用值或错误;
  • http.Response:类包含一个成功的HTTP请求接收到的数据;

在一节会重点讲解Future的用法,如何从Future中获取服务端具体的返回数据。

如何将Response转换成Dart object?

虽然发出网络请求很简单,但如果要使用原始的Future<http.Response>并不简单。为了让我们可以开开心心的写代码,我们可以将http.Response转换成我们自己的Dart对象。

创建一个CommonModel类

首先,我们需要创建一个CommonModel类,它包含我们网络请求的数据。它还将包括一个工厂构造函数,它允许我们可以通过json创建一个CommonModel对象。

class CommonModel {
  final String icon;
  final String title;
  final String url;
  final String statusBarColor;
  final bool hideAppBar;

  CommonModel({this.icon, this.title, this.url, this.statusBarColor, this.hideAppBar});

  factory CommonModel.fromJson(Map<String, dynamic> json) {
    return CommonModel(
      icon: json['icon'],
      title: json['title'],
      url: json['url'],
      statusBarColor: json['statusBarColor'],
      hideAppBar: json['hideAppBar'],
    );
  }
}

http.Response转换成一个CommonModel对象

现在,我们将更新fetchPost函数以返回一个Future<Post>。为此,我们需要:

  1. 使用dart:convert package将响应内容转化为一个json Map;
  2. 使用fromJson工厂函数,将json Map 转化为一个CommonModel对象;
Future<CommonModel> fetchPost() async {
    final response = await http.get('http://www.devio.org/io/flutter_app/json/test_common_model.json');
    final result = json.decode(response.body);
    return new CommonModel.fromJson(result);
  }

如何将请求结果展示在界面上?

图片描述

本节源码

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

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

class MyApp extends StatefulWidget {
  
  State<StatefulWidget> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String showResult = '';

  Future<CommonModel> fetchPost() async {
    final response = await http
        .get('http://www.devio.org/io/flutter_app/json/test_common_model.json');
    final result = json.decode(response.body);
    return CommonModel.fromJson(result);
  }

  
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Http'),
        ),
        body: Column(
          children: <Widget>[
            InkWell(
              onTap: () {
                fetchPost().then((CommonModel value) {
                  setState(() {
                    showResult =
                        '请求结果:
hideAppBar:${value.hideAppBar}
icon:${value.icon}';
                  });
                });
              },
              child: Text(
                '点我',
                style: TextStyle(fontSize: 26),
              ),
            ),
            Text(showResult)
          ],
        ),
      ),
    );
  }
}

class CommonModel {
  final String icon;
  final String title;
  final String url;
  final String statusBarColor;
  final bool hideAppBar;

  CommonModel(
      {this.icon, this.title, this.url, this.statusBarColor, this.hideAppBar});

  factory CommonModel.fromJson(Map<String, dynamic> json) {
    return CommonModel(
      icon: json['icon'],
      title: json['title'],
      url: json['url'],
      statusBarColor: json['statusBarColor'],
      hideAppBar: json['hideAppBar'],
    );
  }
}

在上述代码中我们通过fetchPost().then获取Fluter的返回结果,其实Future可以理解为ES5中的Promise,在接来下的课程中会有对Future的详细讲解。

正在回答 回答被采纳积分+3

2回答

提问者 CrazyCodeBoy 2019-08-01 19:24:52

上文是《基于Http实现网络操作》的辅导文档和源码


2 回复 有任何疑惑可以回复我~
  • 老师,我能引用一部分写自己的学习博客吗
    回复 有任何疑惑可以回复我~ 2022-05-10 17:16:48
henrysheng 2020-06-16 23:45:22

厉害?

0 回复 有任何疑惑可以回复我~
问题已解决,确定采纳
还有疑问,暂不采纳
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号