在Flutter中發起HTTP網絡請求

本頁介紹如何在Flutter中創建HTTP網絡請求。對于socket,請參閱dart:io

注:本篇文檔官方使用的是用dart io中的HttpClient發起的請求,但HttpClient本身功能較弱,很多常用功能都不支持。我們建議您使用dio 來發起網絡請求,它是一個強大易用的dart http請求庫,支持Restful API、FormData、攔截器、請求取消、Cookie管理、文件上傳/下載…...詳情請查看github dio .

發起HTTP請求

http支持位于dart:io,所以要創建一個HTTP client, 我們需要添加一個導入:

import 'dart:io';

var httpClient = new HttpClient();

該 client 支持常用的HTTP操作, such as GET, POST, PUT, DELETE.

處理異步

注意,HTTP API 在返回值中使用了Dart Futures。 我們建議使用async/await語法來調用API。

網絡調用通常遵循如下步驟:

  1. 創建 client.
  2. 構造 Uri.
  3. 發起請求, 等待請求,同時您也可以配置請求headers、 body。
  4. 關閉請求, 等待響應.
  5. 解碼響應的內容.

Several of these steps use Future based APIs. Sample APIs calls for each step above are: 其中的幾個步驟使用基于Future的API。上面步驟的示例:

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();
}

有關完整的代碼示例,請參閱下面的“示例”。

解碼和編碼JSON

使用dart:convert庫可以簡單解碼和編碼JSON。 有關其他的JSON文檔,請參閱JSON和序列化

解碼簡單的JSON字符串并將響應解析為Map:

Map data = JSON.decode(responseBody);
// Assume the response body is something like: ['foo', { 'bar': 499 }]
int barValue = data[1]['bar']; // barValue is set to 499

要對簡單的JSON進行編碼,請將簡單值(字符串,布爾值或數字字面量)或包含簡單值的Map,list等傳給encode方法:

String encodedString = JSON.encode([1, 2, { 'a': null }]);

示例: 解碼 HTTPS GET請求的JSON

以下示例顯示了如何在Flutter應用中對HTTPS GET請求返回的JSON數據進行解碼

It calls the httpbin.com web service testing API, which then responds with your local IP address. Note that secure networking (HTTPS) is used. 它調用httpbin.comWeb service測試API,請注意,使用安全網絡請求(HTTPS)

  1. 運行flutter create,創建一個新的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 = JSON.decode(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'),
            ),
          ],
        ),
      ),
    );
  }
}

API 文檔

有關完整的API文檔,請參閱:


所屬標簽

無標簽

官方入門指南

Flutter官方發布的入門指導,包括了如何在不同的平臺(Windows, Mac, Linux)上搭建開發環境,以及一些入門級的指導,以便您從零開始進入Flutter的世界,同時,一些Flutter的框架API,也是您開發時必不可少的工具書。

從這里進入


25选5玩法中奖