是否有将地图转换为用户定义类对象的标准方法。
在python中你可以做MyClass(** map),它基本上将地图展开为类的构造函数的命名参数。
任何指针/帮助都将不胜感激。
答案 0 :(得分:0)
您也可以使用named constructor手动完成此操作,例如:
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}");
})
);
}
}
答案 1 :(得分:0)
You can use Function.apply。我做了gist来测试链接答案
答案 2 :(得分:0)
采用这种方法,调用代码可以具有类型安全性,street
和city
字段的自动完成功能以及编译时异常。如果您输入错误或将字段视为int
而不是Strings
,则应用将无法编译,而不会在运行时崩溃。
Address.fromJson()
构造函数,用于从地图结构构造新的User实例。
一种toJson()
方法,它将User实例转换为地图。
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;
}