api - 如何从flutter api中获取数据,参数为主体/原始数据
问题描述
**
邮递员代码
**curl --location --request POST 'http://testing.thedivor.com/api/API/GetDistance' --header 'Content-Type: application/json' --data-raw '[ { "id" : "", "placeid": "EiBMZXdpc2hhbSBXYXksIExvbmRvbiBTRTQgMVVZLCBVSyIuKiwKFAoSCXk1YsdYAnZIERCJXqRiE8WPEhQKEgnrjwApXwJ2SBH76fXJO6C02w", "address": "Lewisham Way, London SE4 1UY, UK", "postcode": "SE4 1UY", "outcode": "SE4 1UY", "lattitude": 51.4702816 ,“国家”:“英国”,“城市”:“大伦敦”,“经度”:-0.029187800000045172 },{“_id”:“null”,“placeid”:“”,“地址”:“肯利路, London SW19 3DW, UK", "邮编": "SE23 3RF", "输出代码”:“SE23”,“纬度”:“51.404556”,“国家”:“”,“城市”:“”,“经度”:“-0.194486”}]'
颤振代码
'''var req = await Requests.post('http://testing.thedivor.com/api/API/GetDistance?', headers: {
'Content-Type' : 'application/json'
},
body: body // json 对象 );
print(req.json());
print(req.content().length);'''
解决方案
试试这个:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
home: HomePage(),
),
);
}
class HomePage extends HookWidget {
Future<String> _getDistance() async {
final response = await http.post(
'http://testing.thedivor.com/api/API/GetDistance',
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(params),
);
print(response.body);
return response.statusCode == 200
? jsonDecode(response.body).toString()
: 'Failed to get distance';
}
@override
Widget build(BuildContext context) {
final _distance = useState<String>('');
useEffect(() {
_getDistance().then((d) => _distance.value = d);
return;
}, []);
return Scaffold(
body: Center(
child: Text(_distance.value),
),
);
}
}
final List<Map<String, dynamic>> params = [
{
"id": "",
"placeid":
"EiBMZXdpc2hhbSBXYXksIExvbmRvbiBTRTQgMVVZLCBVSyIuKiwKFAoSCXk1YsdYAnZIERCJXqRiE8WPEhQKEgnrjwApXwJ2SBH76fXJO6C02w",
"address": "Lewisham Way, London SE4 1UY, UK",
"postcode": "SE4 1UY",
"outcode": "SE4 1UY",
"lattitude": 51.4702816,
"country": "United Kingdom",
"city": "Greater London",
"longitude": -0.029187800000045172,
},
{
"_id": "null",
"placeid": "",
"address": "Kenley Road, London SW19 3DW, UK",
"postcode": "SE23 3RF",
"outcode": "SE23",
"lattitude": "51.404556",
"country": "",
"city": "",
"longitude": "-0.194486",
},
];
推荐阅读
- python - 似乎是缓存数据的问题
- webpack - 使用 ES 模块时的 require.context() 替代方案
- javascript - 如何在由 react 创建的 chrome-extension 中获取当前的 Tab URL
- javascript - 当我尝试使用过滤器 vue js 3 时出现白屏
- python - 为什么我的代码不让我打印它运行了多少次?
- python - 比较一个类中的两个对象
- javascript - 如何在 Angular 中使用多个值设置 css 属性?
- sql - 使用 VBA 将 Access 查询附加到 SQL Server 表中
- python - 如果 chromedriver 与 chrome 版本不兼容,如何修复它?
- c++ - 为什么 std::sort 不能与我的 comp 函数一起使用?