美文网首页
在Flutter中发起HTTP网络请求

在Flutter中发起HTTP网络请求

作者: 柳源居士 | 来源:发表于2019-08-07 22:44 被阅读0次
  1. http client添加导入
    类似于angular的HttpClient,使用http请求都需要导入http client。
    dart的http功能位于dart:io中,需要import 进来
import 'dart:io';
//初始化httpClient
var httpClient = new HttpClient();

http支持常见的操作:get、post、put、delete。

注意,HTTP API 在返回值中使用了Dart Futures。 建议使用async/await语法来调用API。

Async and await

The async and await keywords are part of the Dart language’s asynchrony support. They allow you to write asynchronous code that looks like synchronous code and doesn’t use the Future API. An async function is one that has the async keyword before its body. The await keyword works only in async functions.

see the follow:

import 'dart:async';

Future<void> printDailyNewsDigest() async {
  var newsDigest = await gatherNewsReports();
  print(newsDigest);
}

main() {
  printDailyNewsDigest();
  printWinningLotteryNumbers();
  printWeatherForecast();
  printBaseballScore();
}

printWinningLotteryNumbers() {
  print('Winning lotto numbers: [23, 63, 87, 26, 2]');
}

printWeatherForecast() {
  print("Tomorrow's forecast: 70F, sunny.");
}

printBaseballScore() {
  print('Baseball score: Red Sox 10, Yankees 0');
}

const news = '<gathered news goes here>';
const oneSecond = Duration(seconds: 1);

// Imagine that this function is more complex and slow. :)
Future<String> gatherNewsReports() =>
    Future.delayed(oneSecond, () => news);

// Alternatively, you can get news from a server using features
// from either dart:io or dart:html. For example:
//
// import 'dart:html';
//
// Future<String> gatherNewsReportsFromServer() => HttpRequest.getString(
//      'https://www.dartlang.org/f/dailyNewsDigest.txt',
//    );
  • CONSOLE:

Winning lotto numbers: [23, 63, 87, 26, 2]
Tomorrow's forecast: 70F, sunny.
Baseball score: Red Sox 10, Yankees 0
<gathered news goes here>

网络调用通常遵循如下步骤:

  1. 创建 client.
  2. 构造 Uri.
  3. 发起请求, 等待请求,同时您也可以配置请求headers、 body。
  4. 关闭请求, 等待响应.
  5. 解码响应的内容.

例子:

get() async {
  var httpClient = new HttpClient();
  var uri = new Uri.http(
      'example.com', '/path1/path2', {'param1': '42', 'param2': 'foo'});
  var request = await httpClient.getUrl(uri);
  var response = await request.close();
  var responseBody = await response.transform(UTF8.decoder).join();
}

完整的实例:

  1. 新建一个flutter 工程。
  2. 替换lib/main.dart 文件
import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var _ipAddress = 'Unknown';

  _getIPAddress() async {
    var url = 'https://httpbin.org/ip';
    var httpClient = new HttpClient();

    String result;
    try {
      var request = await httpClient.getUrl(Uri.parse(url));
      var response = await request.close();
      if (response.statusCode == HttpStatus.OK) {
        var json = await response.transform(utf8.decoder).join();
        var data = jsonDecode(json);
        result = data['origin'];
      } else {
        result =
            'Error getting IP address:\nHttp status ${response.statusCode}';
      }
    } catch (exception) {
      result = 'Failed getting IP address';
    }

    // 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(() {
      _ipAddress = result;
    });
  }

  @override
  Widget build(BuildContext context) {
    var spacer = new SizedBox(height: 32.0);

    return new Scaffold(
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Text('Your current IP address is:'),
            new Text('$_ipAddress.'),
            spacer,
            new RaisedButton(
              onPressed: _getIPAddress,
              child: new Text('Get IP address'),
            ),
          ],
        ),
      ),
    );
  }
}
  1. 运行


    运行.png
  2. 点击按钮,获得当前IP地址。
    过程解析json格式的返回数据。

{
//返回数据格式
  "origin": "xxx.xxx.xxx.xxx, xxx.xxx.xxx.xxx"
}
···

相关文章

  • 在Flutter中发起HTTP网络请求

    http client添加导入类似于angular的HttpClient,使用http请求都需要导入http cl...

  • Flutter常用的Package

    Flutter搜索库 网络 dio 网络请求 http 网络请求 connectivity 网络状态改变(i...

  • Flutter Dio架构

    在Flutter开发过程中势必要用到网络请求,在Flutter插件库中有Http、Dio等很多优秀的框架,个人比较...

  • Flutter 网络请求 - Http请求

    每个 APP 基本上都离不开网络请求,Flutter 是怎么进行网络请求的?这篇博客简单介绍一下基本的 Http ...

  • Flutter中的http网络请求

    阿里P7移动互联网架构师进阶视频(每日更新中)免费学习请点击:https://space.bilibili.com...

  • Flutter之网络请求

    一、网络请求的方式 在Flutter中常见的网络请求方式有三种:HttpClient、http库、dio库; 1....

  • Flutter网络请求

    一. 网络请求的方式 在Flutter中常见的网络请求方式有三种:HttpClient、http库、dio库; 1...

  • Flutter dio请求DioError [DioErrorT

    一般发生在是安卓9的设备上,在flutter 发起网络请求中,dio报错 解决方案: 在安卓/android/ap...

  • iOS学习笔记——AlamoFire

    前言 在移动开发中,发起http请求几乎是每个app必备的功能。今天就用这篇博客记录iOS发起http请求的示例代...

  • okhttp3和retorfit原理

    网络基础知识:okhttp是一个网络框架,帮我们封装了网络请求中需要重复做的事。 发起网络请求一般都是使用http...

网友评论

      本文标题:在Flutter中发起HTTP网络请求

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