Easily Parse JSON, Create JSON Model Classes, Show in ListView.

By | March 25, 2020

Hi,

This article might be an important one for people who are new into Flutter and others too.
I am going to explain about a simple thing here.

How do you parse complex JSON in Flutter into Dart classes.
Of-course there are libraries in Dart to do that.
But that requires an extra bit of effort to identify each nested classes and create separate JSON classes and generate Model for each of them, another pain would be to link between classes like I did in the below video.

Watch Video Tutorial

Some people may find it difficult to learn.

So here I am sharing an easy way to do this.
This is just going to take a minute to generate Dart Model classes for any complex JSON string.

Here is a very useful service that helps you with this.

https://app.quicktype.io/

You go the above website and paste your proper JSON string on the left and boom!!!, you have generated your Model
classes on the right side. Make sure you choose the right language on the right side to parse data into the language you want.

For Example…

If I am parsing this json data from the below url

https://jsonplaceholder.typicode.com/users

Just copy the whole string, go to https://app.quicktype.io/, select the language on the right side, paste your JSON string on the left side, on the right side is your dart model classes.

If you want to use it…

Create a file named “Users.dart” and copy the generated Dart Model classes into it.

then…

Let’s call the service and get the data…

To do networking, we need the ‘http’ package.
To use the ‘http’ package, add it in the pubspec.yaml file.

Add this under the dependencies section

  http: '0.11.3+17'

Create a file named “Services.dart” and copy the below contents.

//

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

class Services {
  //
  static const String url = 'http://jsonplaceholder.typicode.com/users';

  static Future<List<User>> getUsers() async {
    try {
      final response = await http.get(url);
      if (200 == response.statusCode) {
        final List<User> users = usersFromJson(response.body);
        return users;
      } else {
        return List<User>();
      }
    } catch (e) {
      return List<User>();
    }
  }
}

All you have to do is call the below code.

  usersFromJson(response.body);

Now Let’s show the parsed data of list of users in a ListView.

import 'package:flutter/material.dart';
import 'Services.dart';
import 'Users.dart';

class JsonParseDemo extends StatefulWidget {
  //
  JsonParseDemo() : super();

  @override
  _JsonParseDemoState createState() => _JsonParseDemoState();
}

class _JsonParseDemoState extends State<JsonParseDemo> {
  //
  List<User> _users;
  bool _loading;

  @override
  void initState() {
    super.initState();
    _loading = true;
    Services.getUsers().then((users) {
      setState(() {
        _users = users;
        _loading = false;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_loading ? 'Loading...' : 'Users'),
      ),
      body: Container(
        color: Colors.white,
        child: ListView.builder(
          itemCount: null == _users ? 0 : _users.length,
          itemBuilder: (context, index) {
            User user = _users[index];
            return ListTile(
              title: Text(user.name),
              subtitle: Text(user.email),
            );
          },
        ),
      ),
    );
  }
}

That’s it.

Leave a Reply

Your email address will not be published.