flutter Dio发送post请求
一,导包
dependencies:
flutter:
sdk: flutter
dio: ^4.0.6
二,请求、解析、刷新渲染
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
main() {
runApp(const MaterialApp(
home: H(),
));
}
class H extends StatefulWidget {
const H({super.key});
@override
State<H> createState() => _HState();
}
class _HState extends State<H> {
String _resStr = "";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("抓包测试"),
),
body: Center(
child: Text(
_resStr,
style: const TextStyle(fontSize: 30),
),
),
floatingActionButton:
FloatingActionButton(onPressed: _postRequestFunction));
}
void _postRequestFunction() async {
Dio dio = Dio();
FormData formData = FormData.fromMap({"sourceText": "Who are you?"});
String url = "https://api.oioweb.cn/api/txt/QQFanyi";
Response response = await dio.post(url, data: formData);
setState(() {
_resStr =
json.decode(response.toString())["result"]["targetText"].toString();
});
}
}
三,效果
点击按钮,屏幕中心出现对应的翻译结果