In this tutorial, I use DartJ to generates Dart classes from JSON strings as list of user and display on screen.

Overview

  • Source JSON: jsonplaceholder
https://jsonplaceholder.typicode.com/users
  • generates Dart classes from JSON strings: DartJ

  • fetch JSON string use: dio or http libaray

  # https://pub.dev/packages/equatable
  equatable: ^2.0.3

  # https://pub.dev/packages/dio
  dio: ^4.0.6

  # https://pub.dev/packages/http
  http: ^0.13.5
  • diplay UI: use FutureBuilder

Generates Dart classes from JSON strings with DartJ

  • Step 1: change class name: User

  • Step 2: click button Load JSON from URL

Step 1 & 2

  • Step 3: Put URL: https://jsonplaceholder.typicode.com/users and press button Add

Step 3

  • Step 4: Press button copy and create file user.dart with content file is coppied

Step 4

user.dart file

Fetch/Parser JSON with dio

import 'package:app/user.dart';
import 'package:app/user_repository.dart';
import 'package:dio/dio.dart';

class DioRequest implements UserRepository {
  final Dio _dio = Dio(
    BaseOptions(
      baseUrl: "https://jsonplaceholder.typicode.com/",
      responseType: ResponseType.json,
      receiveTimeout: 3000,
    ),
  );

  @override
  Future<List<User>?> fetchUser() async {
    final Response<List<dynamic>> response = await _dio.get("/users");
    return response.data?.map((e) => User.fromJson(e)).toList(growable: false);
  }
}

Fetch/Parser JSON with http

import 'dart:convert';

import 'package:app/user.dart';
import 'package:app/user_repository.dart';
import 'package:http/http.dart' as http;

class HttpRequest implements UserRepository {
  @override
  Future<List<User>?> fetchUser() async {
    final response =
        await http.get(Uri.parse("https://jsonplaceholder.typicode.com/users"));
    final parsed = json.decode(response.body).cast<Map<String, dynamic>>();

    return parsed.map<User>((json) => User.fromJson(json)).toList();
  }
}

Display list user

FutureBuilder<List<User>?>(
              future: _userRepository?.fetchUser(),
              builder: (
                BuildContext context,
                AsyncSnapshot<List<User>?> snapshot,
              ) {
                if (snapshot.hasData) {
                  final List<User> list = snapshot.data ?? [];
                  if (list.isEmpty) {
                    return const Text("Empty");
                  }

                  return ListView.separated(
                    itemBuilder: (BuildContext context, int index) {
                      final User user = list[index];
                      return Card(
                        child: ListTile(
                          title: Text(user.name ?? ""),
                          subtitle: Text(user.email ?? ""),
                          trailing: Text(user.username ?? ""),
                        ),
                      );
                    },
                    separatorBuilder: (BuildContext context, int index) =>
                        const Divider(),
                    itemCount: list.length,
                  );
                }

                if (snapshot.hasError) {
                  return Text("Error ${snapshot.error?.toString()}");
                }

                return const Center(
                  child: CircularProgressIndicator(
                    strokeWidth: 2,
                  ),
                );
              },
            )

list users

Note

DartJ Tutorial

Thumbnail Photo