如何使用Dart http库flutter实现Post API调用

Fat*_* km 1 api post http dart flutter

我试图在flutter中POST使用http Dart库执行请求.但我无法找到指定请求正文的方法.有人可以帮忙举个例子吗?非常感谢

Hem*_*Raj 15

首先http在你的pubspec.yaml喜欢中指定包

dependencies:
  flutter:
    sdk: flutter

  http: ^0.11.3+16
Run Code Online (Sandbox Code Playgroud)

然后只需导入并使用它.最小的例子如下:

import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;

static Future<Map> getData() async {
  http.Response res = await http.get(url); // get api call
  Map data = JSON.decode(res.body);
  return data;
}

static Future<Map> postData(Map data) async {
  http.Response res = await http.post(url, body: data); // post api call
  Map data = JSON.decode(res.body);
  return data;
}
Run Code Online (Sandbox Code Playgroud)

http.Client为api调用创建和使用它

 //To use Client and Send methods

 http.Client client = new http.Client(); // create a client to make api calls

 Future<Map> getData() async {
  http.Request request = new http.Request("GET", url);  // create get request
  http.StreamedResponse response = await client.send(request); // sends request and waits for response stream
  String responseData = await response.stream.transform(UTF8.decoder).join(); // decodes on response data using UTF8.decoder
  Map data = JSON.decode(responseData); // Parse data from JSON string
  return data;
}
Run Code Online (Sandbox Code Playgroud)

希望有所帮助!