Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map to Class in Dart

Tags:

flutter

dart

Is there a standard way to convert a map to an object of a user defined class?

In Python you can do MyClass(**map) which basically unwraps the map into named arguments of the constructor of the class.

Any pointers/help would be appreciated.

like image 705
user462455 Avatar asked Nov 28 '17 03:11

user462455


2 Answers

You can also achieve this manually by using named constructor like this simple example:

import 'package:flutter/material.dart';

Map myMap = {"Users": [

  {"Name": "Mark", "Email": "mark@email"},


  {"Name": "Rick", "Email": "rick@email"},
]
};

class MyData {
  String name;
  String email;

  MyData.fromJson(Map json){
    this.name = json["Name"];
    this.email = json ["Email"];
  }
}

class UserList extends StatelessWidget {
  MyData data;

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(title: new Text("User List"),),
        body:
        new ListView.builder(
            shrinkWrap: true,
            itemCount: myMap["Users"].length,
            itemBuilder: (BuildContext context, int index) {
              data = new MyData.fromJson(myMap["Users"][index]);
              return new Text("${data.name} ${data.email}");
            })
    );
  }
}

enter image description here

like image 130
Shady Aziza Avatar answered Nov 12 '22 03:11

Shady Aziza


There is no built-in way.
You can use one of the serialization packages like

  • https://pub.dev/packages/json_serializable
  • https://pub.dev/packages/built_value
  • ...
like image 4
Günter Zöchbauer Avatar answered Nov 12 '22 01:11

Günter Zöchbauer