Map to Class in Dart

后端 未结 4 1930
北海茫月
北海茫月 2021-01-11 17:44

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 argumen

相关标签:
4条回答
  • 2021-01-11 18:06

    You can use Function.apply. I made a gist to test it out the linked answer

    0 讨论(0)
  • 2021-01-11 18:17

    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
    • ...
    0 讨论(0)
  • 2021-01-11 18:20

    With this approach, the calling code can have type safety, autocompletion for the street and city fields, and compile-time exceptions. If you make typos or treat the fields as ints instead of Strings, the app won’t compile, instead of crashing at runtime.

    A Address.fromJson() constructor, for constructing a new User instance from a map structure.

    A toJson() method, which converts a User instance into a map.

    class Address {
      String street;
      String city;
    
      Address(this.street, this.city);
    
      Address.fromJson(Map<String, dynamic> json)
          : street = json['street'],
            city = json['city'];
    
      Map<String, dynamic> toJson() =>
          {
            'citstreety': street,
            'city': city,
          };
    }
    
    
    List<Address>  getAddressList(){
    
      Map myMap = {"address": [
        {"street": "Marine Lines", "city": "Mumbai"},
        {"street": "Main Road", "city": "Delhi"},
      ]
      };
    
      var data = myMap["address"];
      List<Address> addressModelList = [];
      for (var u in data) {
        Address address =
        Address.fromJson(u);
        addressModelList.add(address);
      }
      return addressModelList;
    }
    
    0 讨论(0)
  • 2021-01-11 18:29

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

    0 讨论(0)
提交回复
热议问题