1、配置 http
pubspec.yaml
dependencies:
http: ^0.13.4
flutter:
sdk: flutter
- http 库最新插件版本查看:https://pub.dev/packages/http
- 不一定要用最新版本 http,要使用项目所能支持的版本
.dart
import 'package:http/http.dart' as http;
2、示例
(1)工具使用 - postman
- 可以使用 postman 插件中的示例来测试 get/post 请求
(2)代码实现示例
- 点击按钮,发起 Get/Post 请求,并将请求结果展示到界面上
http_page.dart
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class HttpDemo extends StatefulWidget {
const HttpDemo({
super.key});
State<HttpDemo> createState() => _HttpDemoState();
}
class _HttpDemoState extends State<HttpDemo> {
//展示请求结果
var resultShow = "";
//请求结果解析
var resultDecodeShow = "";
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Http 的 post 请求"),
),
body: Column(
children: [
Center(
child: _httpGetButton(),
),
//post 请求按钮 - form
Center(
child: _httpPostFormButton(),
),
//post 请求按钮 - json
Center(
child: _httpPostJsonButton(),
),
Row(
children: [
Expanded(
child: Text(
'请求结果:\n $resultShow',
textAlign: TextAlign.left,
)),
],
),
Row(
children: [
Expanded(
child: Text(
'请求结果(解析):\n $resultDecodeShow',
textAlign: TextAlign.left,
)),
],
),
],
),
);
}
//get 按钮
_httpGetButton() {
return ElevatedButton(onPressed: _doGet, child: const Text('发起 Get 请求'));
}
//post 按钮 - form
_httpPostFormButton() {
return ElevatedButton(
onPressed: _doFormPost, child: const Text('发起 post 请求 - form'));
}
//post 按钮 - json
_httpPostJsonButton() {
return ElevatedButton(
onPressed: _doJsonPost, child: const Text('发起 post 请求 - json'));
}
// utf8 解码
_decodeUtf8(String responseBody) {
var bytes = Uint8List.fromList(responseBody.codeUnits);
String decodeString = utf8.decode<