How to make Http Request and Parse the data to a model class in Flutter

Viewed 2113

I am having a endpoint: https://samples.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=b6907d289e10d714a6e88b30761fae22

It gives a Json Response called:

{"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}

Here i am using the Http library given in docs

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);
  }
}

What I am able to do:

I am able to get the data from server successfully and print the json Response in log.

What I am trying to to:

  1. In android I parse the data using library called GSON into a model class.
  2. How to achieve the same in Flutter ( Looking for a solution that offers similar capability like GSON)
2 Answers

This sample includes a sample how you can fetch a JSON value from the network.

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

It will print

285.514

Since Reflection isn't support in Dart. You cannot just give a class and request the JSON string to be deserialised. You can use Json Serializeble to keep you model class in sync with you JSON. If you need Retrofit like automatice serialisation you can look into Dio which supports this with the help of transformer

Related