首页 > 解决方案 > 如何从flutter api中获取数据,参数为主体/原始数据

问题描述

**

  1. 邮递员代码

    **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);'''

标签: apiflutterdartparameters

解决方案


在此处输入图像描述

试试这个:

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",
  },
];

推荐阅读