Easy Map and List fields from/to Json in Dart

  • flutter
Reading time: 2 minutes

Here we will start with follow up previous ‘bit’ about deep copy, and modify our ‘Child’ model.

class Child {
  final int age;
  final String name;

  Child({this.age, this.name});

  Child copyWith({int age, String name}) {
    return Child(age: age ?? this.age, name: name ?? this.name);

  Child.fromJson(Map<String, dynamic> json)
      : age = json['age'],
        name = json['name'];

  Map<String, dynamic> toJson() => {'age': age, 'name': name};

Now let’s create ‘Adult’ model to have those children, and some friends. We will have Map for children and List for friends to show how to handle both cases in 1 example.

import 'child.dart';

class Adult {
  final String name;
  final Map<String, Child> children;
  final List<Adult> friends;

  Adult({this.name, this.children = const {}, this.friends = const []});

  Adult copyWith(
      {String name, Map<String, Child> children, List<Adult> friends}) {
    return Adult(
        name: name ?? this.name,
        children: children ?? this.children,
        friends: friends ?? this.friends);

  Adult.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        children = Map.fromIterable((json['children'] as List<dynamic>),
            key: (e) => e['name'], value: (e) => Child.fromJson(e['child'])),
        friends = (json['friends'] as List<dynamic>)
            .map((e) => Adult.fromJson(e))

  Map<String, dynamic> toJson() => {
        'name': name,
        'children': children.entries
            .map((e) => {'name': e.key, 'child': e.value.toJson()})
        'friends': friends.map((e) => e.toJson()).toList()

And finally let’s use ‘json’ from ‘dart:convert’ to encode/decode out Adult.

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_examples/example/model/adult.dart';

import 'model/child.dart';

class ModelExample extends StatelessWidget {
  Widget build(BuildContext context) {
    var adult = Adult(name: "Tom", children: {
      "Adam": Child(name: "Adam", age: 7),
      "Natalie": Child(name: "Natalie", age: 5)
    }, friends: [
      Adult(name: "Amy")

    var json = adult.toJson();
    var string = jsonEncode(json);
    var adultRestored = Adult.fromJson(jsonDecode(string));

    return Scaffold(
      body: Center(
        child: Container(
          width: 200,
          height: 200,
          child: ListView(
              children: adultRestored.children.entries
                  .map<Widget>(((e) =>
                      Text("Child - name: ${e.key}, age: ${e.value.age}")))
                        .map<Widget>(((e) => Text("Friend name: ${e.name}")))
                    ..add(Text("Adult name: ${adultRestored.name}"))),

Here we put ListView inside container to put it to centre of the screen. As you can see we restore adult object perfectly. This is final result:

Leave a Reply

Your email address will not be published. Required fields are marked *