映射到Dart中的课程 [英] Map to Class in Dart

查看:100
本文介绍了映射到Dart中的课程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在将地图转换为用户定义类的对象的标准方法?



在Python中,您可以执行MyClass(** map),而该类基本上可以解包



任何指针/帮助都将不胜感激。

解决方案

您也可以使用


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.

解决方案

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

这篇关于映射到Dart中的课程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆