如何进行Http请求并将数据解析为Flutter中的模型类

时间:2019-10-13 13:11:39

标签: http flutter

我有一个端点: https://samples.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=b6907d289e10d714a6e88b30761fae22

它给出了一个名为Json的响应:

{"coord":{"lon":139.01,"lat":35.02},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"base":"stations","main":{"temp":285.514,"pressure":1013.75,"humidity":100,"temp_min":285.514,"temp_max":285.514,"sea_level":1023.22,"grnd_level":1013.75},"wind":{"speed":5.52,"deg":311},"clouds":{"all":0},"dt":1485792967,"sys":{"message":0.0025,"country":"JP","sunrise":1485726240,"sunset":1485763863},"id":1907296,"name":"Tawarano","cod":200}

这里我正在使用docs

中提供的Http库

LoadingScreen.dart

import 'package:clima/services/location.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart';

class LoadingScreen extends StatefulWidget {
  @override
  _LoadingScreenState createState() => _LoadingScreenState();
}

class _LoadingScreenState extends State<LoadingScreen> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getLocation();
  }

  @override
  void deactivate() {
    // TODO: implement deactivate
    super.deactivate();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: RaisedButton(
          onPressed: () {
            //Get the current location
            getLocation();
          },
          child: Text('Get Location'),
        ),
      ),
    );
  }

  Future getLocation() async {
    Location mLoc = Location();
    await mLoc.getLocation();
    print("Co-ordinates fetched");
    print("< -------------------------------------------------- >");
    getData(latitude: mLoc.currentLatitude, longitude: mLoc.currentLongitude);
  }

  void getData({String longitude, String latitude}) async {
    Response response = await get(
        "https://samples.openweathermap.org/data/2.5/weather?lat=$latitude&lon=$longitude&appid=b6907d289e10d714a6e88b30761fae22");
    print(response.body);
  }
}

我能做什么:

我能够从服务器成功获取数据并在日志中打印json响应。

我要做什么:

  1. 在android中,我使用名为GSON的库将数据解析为模型 课。
  2. 如何在Flutter中实现相同目的(寻找一种提供类似功能的解决方案,例如GSON

2 个答案:

答案 0 :(得分:0)

此示例包括一个示例,您如何从网络中获取JSON值。

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

class Location {
  static Future<Map<String, dynamic>> getWeather() async {
    final response = await http.get(
        "https://samples.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=b6907d289e10d714a6e88b30761fae22");
    return json.decode(response.body);
  }
}

void main() async {
  print((await Location.getWeather())["main"]["temp"]);
}

它将打印

  

285.514

答案 1 :(得分:0)

由于Dart不支持Reflection。您不能只提供一个类并请求反序列化JSON字符串。您可以使用Json Serializeble使模型类与JSON保持同步。如果您需要Retrofit(如自动序列化),可以查看Dio,它在转换器的帮助下对此提供支持