type 'String' is not a subtype of type 'int' of 'index' while getting media fields using the instagram API - json

i'm trying to get media fields from the instagram api and i'm getting this error
type 'String' is not a subtype of type 'int' of 'index'
here's Homepage.dart :
import 'package:flutter/material.dart';
import 'package:get_storage/get_storage.dart';
import 'package:insta_details/models/data.dart';
import 'package:insta_details/utils/custom_dio_mixin.dart';
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
static String id = "HomePage";
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> with CustomDioMixin {
bool loading = true;
bool error = false;
late Media media;
#override
void initState() {
super.initState();
getData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: loading
? const Center(
child: CircularProgressIndicator(),
)
: error
? const Center(
child: Text('An error has occurred!'),
)
: ListView.builder(
itemBuilder: (context, index) => MediaWidget(
media: media,
),
),
),
);
}
Future<void> getData() async {
try {
final storage = GetStorage();
final token = storage.read("accessToken");
Media? media;
final response = await dio.get(
'https://graph.instagram.com/me/media?fields=id,caption,media_url,timestamp&access_token=$token',
);
print("get data response => ${response.statusCode} ${response.data}");
Media mediadata = Media.fromJson(response.data);
print(mediadata);
} catch (e) {
print("get data failed");
print(e);
setState(() {
error = true;
});
} finally {
setState(() {
loading = false;
});
}
}
}
class MediaWidget extends StatelessWidget {
final Media media;
const MediaWidget({Key? key, required this.media}) : super(key: key);
#override
Widget build(BuildContext context) {
return GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
itemCount: 6,
itemBuilder: (context, index) {
return Image.network(media.mediaUrl);
},
);
}
}
and here data.dart :
class Media {
Media({
required this.id,
required this.caption,
required this.mediaUrl,
required this.timestamp,
});
String id;
String caption;
String mediaUrl;
String timestamp;
factory Media.fromJson(Map<String, dynamic> json) => Media(
id: json["data"]["id"] as String,
caption: json["data"]["caption"] as String,
mediaUrl: json["data"]["media_url"] as String,
timestamp: json["data"]["timestamp"] as String,
);
Map<String, dynamic> toJson() => {
"id": id,
"caption": caption,
"media_url": mediaUrl,
"timestamp": timestamp,
};
}
and the log :
I/flutter ( 5699): get data response => 200 {data: [{id: 18106429915287733, caption: cabin in the woods, media_url: https://scontent.cdninstagram.com/v/t51.29350-15/272751472_358111429123560_6575694365508668882_n.jpg?_nc_cat=100&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=0omRv4cUGtwAX8bbmC7&_nc_ht=scontent.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT_fqBkL5ykJXWRj7Rcy4nCnyuXEKh-8o0TX9FJkJ4dcfQ&oe=61FD881A, timestamp: 2022-01-27T11:15:07+0000}, {id: 17917394609104775, caption: Truck, media_url: https://scontent.cdninstagram.com/v/t51.29350-15/272701475_1080001635904581_1705933746471766077_n.jpg?_nc_cat=107&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=ZfSpeg7rHn4AX89PW0c&_nc_ht=scontent.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT_Qbj7zOH-UEzplA9mdIrCHaeb9EBBuz1RjKJclN9Q2RA&oe=61FE9898, timestamp: 2022-01-27T11:14:26+0000}, {id: 17921627228176014, caption: Gaara, media_url: https://scontent.cdninstagram.com/v/t51.29350-15/272660463_892749041374464_5507853711157520506_n.jpg?_nc_cat=101&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=va5seINOs-4AX9vOy4L&_nc_ht=scontent.cdninst
I/flutter ( 5699): get data failed
I/flutter ( 5699): type 'String' is not a subtype of type 'int' of 'index'
my JSON response :
{
"data": [
{
"id": "18106429915287733",
"caption": "cabin in the woods",
"media_type": "IMAGE",
"media_url": "https://scontent-iad3-1.cdninstagram.com/v/t51.29350-15/272751472_358111429123560_6575694365508668882_n.jpg?_nc_cat=100&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=xXGDvxMsycAAX_U_-55&_nc_ht=scontent-iad3-1.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT-EuNnLxrBSNirBOl1prRXlHepdhQqUjYRBEv3Zh_Ld6Q&oe=61FD881A",
"username": "parekchampl",
"timestamp": "2022-01-27T11:15:07+0000"
},
{
"id": "17917394609104775",
"caption": "Truck",
"media_type": "IMAGE",
"media_url": "https://scontent-iad3-1.cdninstagram.com/v/t51.29350-15/272701475_1080001635904581_1705933746471766077_n.jpg?_nc_cat=107&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=ZfSpeg7rHn4AX_J_eQs&_nc_ht=scontent-iad3-1.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT92hbhb0XK56kxC-_e8kpM6QFLazDH0TDCfdIdEIpNinw&oe=61FC9E58",
"username": "parekchampl",
"timestamp": "2022-01-27T11:14:26+0000"
},
{
"id": "17921627228176014",
"caption": "Gaara",
"media_type": "IMAGE",
"media_url": "https://scontent-iad3-1.cdninstagram.com/v/t51.29350-15/272660463_892749041374464_5507853711157520506_n.jpg?_nc_cat=101&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=va5seINOs-4AX_SB6jL&_nc_ht=scontent-iad3-1.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT8rviJ6wbaT0yF1Hq2VprtnQ-W0rARS5oxIr52MIhC0Rw&oe=61FD720B",
"username": "parekchampl",
"timestamp": "2022-01-27T11:13:42+0000"
},
{
"id": "18024346318348836",
"caption": "Marceline",
"media_type": "IMAGE",
"media_url": "https://scontent-iad3-1.cdninstagram.com/v/t51.29350-15/272807293_686124672409566_4991399943515126026_n.jpg?_nc_cat=106&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=JMfTMSD_1c8AX-m5WDx&_nc_ht=scontent-iad3-1.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT_P38eDVtcqEYL053wGPkLjhHStLCh7_fgFnCg4LcH1yA&oe=61FD1F82",
"username": "parekchampl",
"timestamp": "2022-01-27T11:13:02+0000"
},
{
"id": "17859174368680579",
"caption": "uchiha shisui",
"media_type": "IMAGE",
"media_url": "https://scontent-iad3-1.cdninstagram.com/v/t51.29350-15/272721151_749467822692662_5191995429373550055_n.jpg?_nc_cat=111&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=01A68vtgY-kAX-ux6iB&_nc_ht=scontent-iad3-1.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT9oWtK9VWV8j3c8Ij2YXctIpuh9sC-NJO1BLCwFObDDSA&oe=61FE0B03",
"username": "parekchampl",
"timestamp": "2022-01-27T11:12:35+0000"
},
{
"id": "17917757036265369",
"caption": "Son and Father",
"media_type": "IMAGE",
"media_url": "https://scontent-iad3-1.cdninstagram.com/v/t51.29350-15/272660947_1107548556714461_1575953024252145708_n.jpg?_nc_cat=100&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=Mzj5Wp9sv_oAX_2Z4Nv&_nc_ht=scontent-iad3-1.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT8Ywp3DUIemrIoCPajFvivfTG_-AWvEs2fpkngYXUN6Lg&oe=61FE17A1",
"username": "parekchampl",
"timestamp": "2022-01-27T11:11:47+0000"
}
],
"paging": {
"cursors": {
"before": "QVFIUnpEcERJTXdYRjd3SVp3MUo2U25UeWhhdlgxQ2xMY0diR2pYVFhCVl9TUUhlM1hqYllKWUpEWXJtYW5RWW41am1Lc3B4U281TU14ZAFoxSVBkMVRsZAkZAB",
"after": "QVFIUkgtUzExdDNsYzgwUFhGdnRXQlB6N0JkZATVFeU1DVkhzXzduLTF1RklpR1A5MDNMeWVEemtzdE15OVBlYmpYb29mQlVtdDJsX1N2SUcwa2ZAkc21jblZAn"
}
}
}

According to the documentation : https://developers.facebook.com/docs/instagram-basic-display-api/reference/media ,every field is a String
factory Media.fromJson(Map<String, dynamic> json) => Media(
id: json["data"]["id"] as String,
caption: json["data"]["caption"] as String,
mediaUrl: json["data"]["media_url"] as String,
timestamp: json["data"]["timestamp"] as String,
);
Or change to something like below:
factory Media.fromJson(Map<String, dynamic> json) => Media(
id: int.parse(json["data"]["id"] as String),
caption: json["data"]["caption"] as String,
mediaUrl: json["data"]["media_url"] as String,
timestamp: DateTime.parse(json["data"]["timestamp"] as String),
);

The value of your data key is a List not a Map. Here's an example:
const responseData =
{
"data":[
{
"id":"18106429915287733",
"caption":"cabin in the woods",
"media_type":"IMAGE",
"media_url":"https://scontent-iad3-1.cdninstagram.com/v/t51.29350-15/272751472_358111429123560_6575694365508668882_n.jpg?_nc_cat=100&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=xXGDvxMsycAAX_U_-55&_nc_ht=scontent-iad3-1.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT-EuNnLxrBSNirBOl1prRXlHepdhQqUjYRBEv3Zh_Ld6Q&oe=61FD881A",
"username":"parekchampl",
"timestamp":"2022-01-27T11:15:07+0000"
},
{
"id":"17917394609104775",
"caption":"Truck",
"media_type":"IMAGE",
"media_url":"https://scontent-iad3-1.cdninstagram.com/v/t51.29350-15/272701475_1080001635904581_1705933746471766077_n.jpg?_nc_cat=107&ccb=1-5&_nc_sid=8ae9d6&_nc_ohc=ZfSpeg7rHn4AX_J_eQs&_nc_ht=scontent-iad3-1.cdninstagram.com&edm=ANo9K5cEAAAA&oh=00_AT92hbhb0XK56kxC-_e8kpM6QFLazDH0TDCfdIdEIpNinw&oe=61FC9E58",
"username":"parekchampl",
"timestamp":"2022-01-27T11:14:26+0000"
}
]
};
void main() {
final mediaList = responseData["data"]!.map((entry) => Media.fromJson(entry))
.toList();
for (var media in mediaList) {
print(media.id);
}
}
class Media {
Media({
required this.id,
required this.caption,
required this.mediaUrl,
required this.timestamp,
});
int? id;
String caption;
String mediaUrl;
String timestamp;
factory Media.fromJson(Map<String, dynamic> json) {
return Media(
id: int.tryParse(json["id"]),
caption: json["caption"],
mediaUrl: json["media_url"],
timestamp: json["timestamp"],
);
}
Map<String, dynamic> toJson() => {
"id": id.toString(),
"caption": caption,
"media_url": mediaUrl,
"timestamp": timestamp,
};
}

On your model class id is nullable int, but you are receiving id as String.
You can typecast string to int On your Media.fromJson, while the id accept null value, if something wrong happen id will get null value.
factory Media.fromJson(Map<String, dynamic> json) => Media(
id: int.tryParse(json["data"]["id"]),
And for toJson pass id as String
Map<String, dynamic> toJson() => {
"id": id.toString(),
More about int.tryParse.

Related

How can i pass this complex Json MAP Data into flutter Listview

i am new to flutter, and i meet this API with complex "MAP" json. What i want is to display the list of countries with their details in flutter listview, How can i achieve that? Most of answers explain about "LIST" json.
{
"status": "Request is successful",
"message": null,
"data": {
"page": 1,
"last_page": 125,
"page_size": 2,
"countries": [
{
"id": "1",
"attributes": {
"name": "Grenada",
"code": "GD",
"subregion": "Caribbean",
"flag": "https://flagcdn.com/gd.svg",
"postalcode": "",
"latitude": "12.11666666",
"longitude": "-61.66666666",
"createdAt": "2023-01-11T22:15:40.000000Z",
"updatedAt": "2023-01-11T22:15:40.000000Z"
}
},
{
"id": "2",
"attributes": {
"name": "Malaysia",
"code": "MY",
"subregion": "South-Eastern Asia",
"flag": "https://flagcdn.com/my.svg",
"postalcode": "^(\\d{5})$",
"latitude": "2.5",
"longitude": "112.5",
"createdAt": "2023-01-11T22:15:40.000000Z",
"updatedAt": "2023-01-11T22:15:40.000000Z"
}
}
]
}
}
I found this GitHub project with these files json, modelClass Mainclass which relate with the concept but mine is has got one extra braces (map) so i do not know how to achieve the goal.
if there any suggestion or best way to code please help me.
this is how they created in model class but, but it does not work with me.
class Product {
final List<Result> results;
Product({this.results});
factory Product.fromJson(Map<String, dynamic> data) {
var list = data['data']['result'] as List;
List<Result> resultList = list.map((e) => Result.fromJson(e)).toList();
return Product(
results: resultList,
);
}
}
what i have done is
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key});
#override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
var data_from_link;
getData() async {
final String link = 'myurl';
data_from_link = await http.get(Uri.parse(link), headers: {"Accept": "application/json"});
final res = jsonDecode(data_from_link.body) as Map<String, dynamic>;
final List<Country> list= (res['data']['countries'] as List<dynamic>).map((e) => Country.fromJson(e))
.toList();
}
#override
void initState() {
super.initState();
getData();
}
#override
Widget build(BuildContext context) {
final res = jsonDecode(data_from_link.body) as Map<String, dynamic>;
final List<Country> list= (res['data']['countries'] as List<dynamic>).map((e) => Country.fromJson(e))
.toList();
return ListView.builder(
itemCount: list.length,
itemBuilder: (_, i) => ListTile(
title: Text(
list![i].attributes.name,
),
subtitle: Text(list![i].attributes.code),
)
);
}
}
You can create two classes for Country and Attribute
class Country {
const Country({required this.id, required this.attributes});
/// Creates a Country from Json map
factory Country.fromJson(Map<String, dynamic> json) => Country(
id: json['id'] as String,
attribute:
Attribute.fromJson(json['attributes'] as Map<String, dynamic>),
);
/// A description for id
final String id;
final Attribute attributes;
}
class Attribute {
const Attribute({
required this.name,
required this.code,
required this.createdAt,
required this.updatedAt,
});
/// Creates a Attribute from Json map
factory Attribute.fromJson(Map<String, dynamic> json) => Attribute(
name: json['name'] as String,
code: json['code'] as String,
createdAt: DateTime.parse(json['createdAt'] as String),
updatedAt: DateTime.parse(json['updatedAt'] as String),
);
final String name;
final String code;
final DateTime createdAt;
final DateTime updatedAt;
}
when decoding:
final res = jsonDecode(json) as Map<String, dynamic>;
final List<Country> list = (res['data']['countries'] as
List<dynamic>)
.map((e) => Country.fromJson(e))
.toList();
Thank you but how can i print or call data from country attribute
after decoding because when i try something like Print
(list.country.attribute.name) . I fail. My goal is to display on
Listview
You can use it like this:
ListView.builder(
itemCount: list.length,
itemBuilder: (_, i) => ListTile(
title: Text(
list[i].attributes.name,
),
subtitle: Text(list[i].attributes.code),
)),
UPDATE
import 'package:flutter/material.dart';
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key});
#override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
late Future<List<Country>> futureList;
Future<List<Country>?> getData() async {
final String link = 'yoururl';
final res = await http
.get(Uri.parse(link), headers: {"Accept": "application/json"});
if (response.statusCode == 200) {
final List<Country> list = (res['data']['countries'] as List<dynamic>)
.map((e) => Country.fromJson(e))
.toList();
return list;
} else {
throw Exception('Failed to fetch data');
}
}
#override
void initState() {
super.initState();
futureList = getData();
}
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: futureList,
builder: (context, snapshot) {
if (snapshot.hasData) {
final list = snapshot.data;
return ListView.builder(
itemCount: list!.length,
itemBuilder: (_, i) => ListTile(
title: Text(
list![i].attributes.name,
),
subtitle: Text(list![i].attributes.code),
),
);
} else if (snapshot.hasError) {
return const Text('error fetching data');
}
return const CircularProgressIndicator();
},
);
}
}

Flutter - Parse multiple json array and set to list

HERE IS THE JSON OF RESPONSE BODY:
{
"status": "success",
"contents": [{
"id": "15",
"cname": "DOGS",
"dogs_image": "1638695967-rtyyyt.jpg",
"cat_image": "1638695967-jhjjj.jpg",
"sub_category": [{
"subcatid": "36",
"cat_id": "15",
"sub_category_name": "Accessories",
"banner": null,
"image": "1638695982-ACCESORIE.jpg"
}, {
"subcatid": "39",
"cat_id": "15",
"sub_category_name": "Beds",
"banner": null,
"image": "1638695982-ACCESORIE.jpg"
}]
}, {
"id": "14",
"cname": "CATS",
"dogs_image": "1638695967-rtyyyt.jpg",
"cat_image": "1638695967-jhjjj.jpg",
"sub_category": [{
"subcatid": "47",
"cat_id": "14",
"sub_category_name": "Accessories",
"banner": null,
"image": "1638695982-ACCESORIE.jpg"
}]
}]
}
// API call to get the above json data:
Future<List<CatListData>> dashboardDataAPI(http.Client client) async {
final response = await client.get(Uri.parse(Utilities.BASE_URL));
List list = json.decode(response.body)['contents'];
return parsePhotos(list.toString());
}
// A function that converts a response body into a List
List<CatListData> parsePhotos(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<CatListData>((json) => CatListData.fromJson(json)).toList();
}
// Cat List Class
class CatListData{
final String id;
final String cName;
final String dogImage;
final String catImage;
final List<SubCatListData> subCatListDataList;
CatListData({required this.id, required this.cName, required this.dogImage, required this.catImage, required this.subCatListDataList});
factory CatListData.fromJson(Map<String, dynamic> json) {
return CatListData(
id: json['id'] as String,
cName: json['cname'] as String,
dogImage: json['dogs_image'] as String,
catImage: json['cat_image'] as String,
subCatListDataList: List<SubCatListData>.from(json['sub_category'] as Iterable),
);
}
}
// Sub Cat Class
class SubCatListData{
final String subCatId;
final String catId;
final String subCategoryName;
final String banner;
final String image;
SubCatListData({required this.subCatId, required this.catId, required this.subCategoryName, required this.banner, required this.image});
factory SubCatListData.fromJson(Map<String, dynamic> json) {
return SubCatListData(
subCatId: json['subcatid'] as String,
catId: json['cat_id'] as String,
subCategoryName: json['sub_category_name'] as String,
banner: json['banner'] as String,
image: json['image'] as String,
);
}
}
Here showing null when I print snapshot
Container(
child: FutureBuilder<List<CatListData>>(
future: dashboardDataAPI(http.Client()),
builder: (context, snapshot) {
print("Response:: "+snapshot.data.toString());
if (snapshot.hasData) {
return PhotosList(photos: snapshot.data!);
}else if(snapshot.hasError){
return const Center(
child: Text('An error has occurred!'),);
}else{
return const Center(
child: CircularProgressIndicator(),
);
}
},
),
)
Please let me know how I can fix this issue and parse the multiple json array data into the list.
Thanks
I believe the problem happens on this line on the CatListData.fromJson constructor:
subCatListDataList: List<SubCatListData>.from(json['sub_category'] as Iterable),
you never call SubCatListData.fromJson, I believe this will work better for your assignment:
subCatListDataList: (json['sub_category'] as Iterable).map<SubCatListData>(
(value) => SubCatListData.fromJson(value as Map<String, dynamic>),
),

How to store complex json data in model class in flutter

Here is my code"
I've tried printing values.
I got value in token.
I'm able to iterate through the each value present in API using for each loop but data isn't storing into my model class.
SharedPreferences prefs = await SharedPreferences.getInstance();
final token = prefs.getString("token") ?? null;
final userId = prefs.getInt("id") ?? null;
List<GroupListData> grpDataList = [];
if (token != null) {
String url = "${NetworkRequest.baseUrl}/api/group_list";
var groupRes = await http.post(Uri.parse(url), body: {
"user_id": '$userId'
}, headers: {
//'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token',
});
//print(groupRes.body);
if (groupRes.statusCode == 200) {
final rowJsonData = jsonDecode(groupRes.body);
GroupListData groupListData;
List<dynamic> groupLists = rowJsonData['data'];
groupLists.forEach((d) {
print(d['id']);
groupListData = GroupListData(
id: d['id'],
groupName: d["groupName"],
status: d["status"],
createdAt: d["createdAt"],
updatedAt: d["updatedAt"],
);
grpDataList.add(groupListData);
});
for (var d in rowJsonData['data']) {
print(d);
}
} else {
print('grpResp ${groupRes.statusCode}');
}
//print('Token : $token');
} else {
print('token is empty');
}
print(grpDataList);
return grpDataList;
}
here this is my JSON Data
{
"data": [
{
"id": 1,
"group_name": "payroll",
"status": 1,
"created_at": "2021-07-20 08:27:31",
"updated_at": "2021-07-20 10:09:11"
},
{
"id": 2,
"group_name": "New Recuritment",
"status": 1,
"created_at": "2021-07-20 11:21:40",
"updated_at": "2021-07-20 11:21:40"
}
],
"message": "Data Found",
"status": 200
}
here is my model class
i think that there is issue in my model class
i am not able to understand
class GroupListData {
GroupListData({
this.id,
this.groupName,
this.status,
this.createdAt,
this.updatedAt,
});
int? id;
String? groupName;
int? status;
DateTime? createdAt;
DateTime? updatedAt;
factory GroupListData.fromJson(Map<String, dynamic> json) => GroupListData(
id: json["id"],
groupName: json["group_name"],
status: json["status"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"group_name": groupName,
"status": status,
"created_at": createdAt!.toIso8601String(),
"updated_at": updatedAt!.toIso8601String(),
};
}
here is my ui code
FutureBuilder<List<GroupListData>>(
future: getGroupListData(),
builder: (BuildContext context,
AsyncSnapshot<List<GroupListData>> snapshot) {
if (snapshot.data == null) {
return Container(
child: Center(
child: Text('Loading...'),
),
);
}
return ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: snapshot.data!.length,
itemBuilder: (BuildContext context, int index) {
return RoundedCard(
str: '${snapshot.data![index].groupName}', ///.groupName always return null value
onTap: () {
Navigator.push(
context,
PageTransition(
type: PageTransitionType.rightToLeft,
child: FeedPage(feedTitle: 'Marketing Team'),
inheritTheme: true,
ctx: context),
);
print('Marketing card');
});
});
},
),
thanks in advance
You dont need to convert your json to modal by yourself.
if the Flutter SDK < 2.0 (Null safety) then please use this online json converter https://javiercbk.github.io/json_to_dart/
otherwise use this online json Converter for Flutter > 2.0 https://app.quicktype.io/

Flutter fetch data from the internet

I'm trying to get some information from here such as name,avatar_url,stargazers_count and description
{
"total_count": 18689015,
"incomplete_results": true,
"items": [
{
"id": 215415332,
"node_id": "MDEwOlJlcG9zaXRvcnkyMTU0MTUzMzI=",
"name": "HackingNeuralNetworks",
"full_name": "Kayzaks/HackingNeuralNetworks",
"private": false,
"owner": {
"login": "Kayzaks",
"id": 11071537,
"node_id": "MDQ6VXNlcjExMDcxNTM3",
"avatar_url": "https://avatars1.githubusercontent.com/u/11071537?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/Kayzaks",
"html_url": "https://github.com/Kayzaks",
"followers_url": "https://api.github.com/users/Kayzaks/followers",
"following_url": "https://api.github.com/users/Kayzaks/following{/other_user}",
"gists_url": "https://api.github.com/users/Kayzaks/gists{/gist_id}",
"starred_url": "https://api.github.com/users/Kayzaks/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/Kayzaks/subscriptions",
"organizations_url": "https://api.github.com/users/Kayzaks/orgs",
"repos_url": "https://api.github.com/users/Kayzaks/repos",
"events_url": "https://api.github.com/users/Kayzaks/events{/privacy}",
"received_events_url": "https://api.github.com/users/Kayzaks/received_events",
"type": "User",
"site_admin": false
},
"html_url": "https://github.com/Kayzaks/HackingNeuralNetworks",
"description": "A small course on exploiting and defending neural networks",
"fork": false,
....
....
At run time I get this message error :
type _internalLine HashMap<String , dynamic> is not a subtype of type List<dynamic> in type cast
here's the full code :
RepoItem:
class RepoItem {
Owner owner;
String name;
String stargazers_count;
String description;
RepoItem._({this.owner, this.name, this.stargazers_count, this.description});
factory RepoItem.fromJson(Map<String, dynamic> json) {
return new RepoItem._(
owner: json['owner'],
name: json['name'],
stargazers_count: json['stargazers_count'],
description: json['description']);
}
}
PageState:
class _MyHomePageState extends State<MyHomePage> {
List<RepoItem> list = List();
var isLoading = false;
Future<List<RepoItem>> _fetchData() async {
final response = await http.get(
"https://api.github.com/search/repositories?q=created:%3E2018-10-22&sort=stars&order=desc");
list = (json.decode(response.body) as List)
.map((data) => new RepoItem.fromJson(data.body))
.toList();
return list;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Container(
child: FutureBuilder(
future: _fetchData(),
builder: (BuildContext context, AsyncSnapshot asyncSnapshot) {
if (asyncSnapshot.hasError) {
return Container(
child: Center(
child: Text(asyncSnapshot.error.toString()),
),
);
}
if (asyncSnapshot.data == null) {
return Container(
child: Center(
child: Text("Loading ..."),
),
);
} else {
return ListView.builder(
itemCount: asyncSnapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(asyncSnapshot.data[index].name),
leading: CircleAvatar(
backgroundImage: NetworkImage(
asyncSnapshot.data[index].owner.avatar_url),
),
subtitle: Text(asyncSnapshot.data[index].description),
);
},
);
}
},
),
),
);
}
}
You can copy paste run full code below
You can parse with payloadFromJson, you can see Payload class in full code
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
...
var items = snapshot.data.items;
return ListView.builder(
itemCount: items.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(items[index].name),
leading: CircleAvatar(
backgroundImage:
NetworkImage(items[index].owner.avatarUrl),
),
subtitle: Text(items[index].description),
);
},
);
working demo
full code
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
// To parse this JSON data, do
//
// final payload = payloadFromJson(jsonString);
import 'dart:convert';
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
String payloadToJson(Payload data) => json.encode(data.toJson());
class Payload {
String totalCount;
bool incompleteResults;
List<Item> items;
Payload({
this.totalCount,
this.incompleteResults,
this.items,
});
factory Payload.fromJson(Map<String, dynamic> json) => Payload(
totalCount: json["total_count"].toString(),
incompleteResults: json["incomplete_results"],
items: List<Item>.from(json["items"].map((x) => Item.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"total_count": totalCount,
"incomplete_results": incompleteResults,
"items": List<dynamic>.from(items.map((x) => x.toJson())),
};
}
class Item {
String id;
String nodeId;
String name;
String fullName;
bool private;
Owner owner;
String htmlUrl;
String description;
bool fork;
String url;
String forksUrl;
String keysUrl;
String collaboratorsUrl;
String teamsUrl;
String hooksUrl;
String issueEventsUrl;
String eventsUrl;
String assigneesUrl;
String branchesUrl;
String tagsUrl;
String blobsUrl;
String gitTagsUrl;
String gitRefsUrl;
String treesUrl;
String statusesUrl;
String languagesUrl;
String stargazersUrl;
String contributorsUrl;
String subscribersUrl;
String subscriptionUrl;
String commitsUrl;
String gitCommitsUrl;
String commentsUrl;
String issueCommentUrl;
String contentsUrl;
String compareUrl;
String mergesUrl;
String archiveUrl;
String downloadsUrl;
String issuesUrl;
String pullsUrl;
String milestonesUrl;
String notificationsUrl;
String labelsUrl;
String releasesUrl;
String deploymentsUrl;
DateTime createdAt;
DateTime updatedAt;
DateTime pushedAt;
String gitUrl;
String sshUrl;
String cloneUrl;
String svnUrl;
String homepage;
int size;
int stargazersCount;
int watchersCount;
String language;
bool hasIssues;
bool hasProjects;
bool hasDownloads;
bool hasWiki;
bool hasPages;
int forksCount;
dynamic mirrorUrl;
bool archived;
bool disabled;
int openIssuesCount;
License license;
int forks;
int openIssues;
int watchers;
DefaultBranch defaultBranch;
double score;
Item({
this.id,
this.nodeId,
this.name,
this.fullName,
this.private,
this.owner,
this.htmlUrl,
this.description,
this.fork,
this.url,
this.forksUrl,
this.keysUrl,
this.collaboratorsUrl,
this.teamsUrl,
this.hooksUrl,
this.issueEventsUrl,
this.eventsUrl,
this.assigneesUrl,
this.branchesUrl,
this.tagsUrl,
this.blobsUrl,
this.gitTagsUrl,
this.gitRefsUrl,
this.treesUrl,
this.statusesUrl,
this.languagesUrl,
this.stargazersUrl,
this.contributorsUrl,
this.subscribersUrl,
this.subscriptionUrl,
this.commitsUrl,
this.gitCommitsUrl,
this.commentsUrl,
this.issueCommentUrl,
this.contentsUrl,
this.compareUrl,
this.mergesUrl,
this.archiveUrl,
this.downloadsUrl,
this.issuesUrl,
this.pullsUrl,
this.milestonesUrl,
this.notificationsUrl,
this.labelsUrl,
this.releasesUrl,
this.deploymentsUrl,
this.createdAt,
this.updatedAt,
this.pushedAt,
this.gitUrl,
this.sshUrl,
this.cloneUrl,
this.svnUrl,
this.homepage,
this.size,
this.stargazersCount,
this.watchersCount,
this.language,
this.hasIssues,
this.hasProjects,
this.hasDownloads,
this.hasWiki,
this.hasPages,
this.forksCount,
this.mirrorUrl,
this.archived,
this.disabled,
this.openIssuesCount,
this.license,
this.forks,
this.openIssues,
this.watchers,
this.defaultBranch,
this.score,
});
factory Item.fromJson(Map<String, dynamic> json) => Item(
id: json["id"].toString(),
nodeId: json["node_id"],
name: json["name"],
fullName: json["full_name"],
private: json["private"],
owner: Owner.fromJson(json["owner"]),
htmlUrl: json["html_url"],
description: json["description"] == null ? null : json["description"],
fork: json["fork"],
url: json["url"],
forksUrl: json["forks_url"],
keysUrl: json["keys_url"],
collaboratorsUrl: json["collaborators_url"],
teamsUrl: json["teams_url"],
hooksUrl: json["hooks_url"],
issueEventsUrl: json["issue_events_url"],
eventsUrl: json["events_url"],
assigneesUrl: json["assignees_url"],
branchesUrl: json["branches_url"],
tagsUrl: json["tags_url"],
blobsUrl: json["blobs_url"],
gitTagsUrl: json["git_tags_url"],
gitRefsUrl: json["git_refs_url"],
treesUrl: json["trees_url"],
statusesUrl: json["statuses_url"],
languagesUrl: json["languages_url"],
stargazersUrl: json["stargazers_url"],
contributorsUrl: json["contributors_url"],
subscribersUrl: json["subscribers_url"],
subscriptionUrl: json["subscription_url"],
commitsUrl: json["commits_url"],
gitCommitsUrl: json["git_commits_url"],
commentsUrl: json["comments_url"],
issueCommentUrl: json["issue_comment_url"],
contentsUrl: json["contents_url"],
compareUrl: json["compare_url"],
mergesUrl: json["merges_url"],
archiveUrl: json["archive_url"],
downloadsUrl: json["downloads_url"],
issuesUrl: json["issues_url"],
pullsUrl: json["pulls_url"],
milestonesUrl: json["milestones_url"],
notificationsUrl: json["notifications_url"],
labelsUrl: json["labels_url"],
releasesUrl: json["releases_url"],
deploymentsUrl: json["deployments_url"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
pushedAt: DateTime.parse(json["pushed_at"]),
gitUrl: json["git_url"],
sshUrl: json["ssh_url"],
cloneUrl: json["clone_url"],
svnUrl: json["svn_url"],
homepage: json["homepage"] == null ? null : json["homepage"],
size: json["size"],
stargazersCount: json["stargazers_count"],
watchersCount: json["watchers_count"],
language: json["language"] == null ? null : json["language"],
hasIssues: json["has_issues"],
hasProjects: json["has_projects"],
hasDownloads: json["has_downloads"],
hasWiki: json["has_wiki"],
hasPages: json["has_pages"],
forksCount: json["forks_count"],
mirrorUrl: json["mirror_url"],
archived: json["archived"],
disabled: json["disabled"],
openIssuesCount: json["open_issues_count"],
license:
json["license"] == null ? null : License.fromJson(json["license"]),
forks: json["forks"],
openIssues: json["open_issues"],
watchers: json["watchers"],
defaultBranch: defaultBranchValues.map[json["default_branch"]],
score: json["score"],
);
Map<String, dynamic> toJson() => {
"id": id,
"node_id": nodeId,
"name": name,
"full_name": fullName,
"private": private,
"owner": owner.toJson(),
"html_url": htmlUrl,
"description": description == null ? null : description,
"fork": fork,
"url": url,
"forks_url": forksUrl,
"keys_url": keysUrl,
"collaborators_url": collaboratorsUrl,
"teams_url": teamsUrl,
"hooks_url": hooksUrl,
"issue_events_url": issueEventsUrl,
"events_url": eventsUrl,
"assignees_url": assigneesUrl,
"branches_url": branchesUrl,
"tags_url": tagsUrl,
"blobs_url": blobsUrl,
"git_tags_url": gitTagsUrl,
"git_refs_url": gitRefsUrl,
"trees_url": treesUrl,
"statuses_url": statusesUrl,
"languages_url": languagesUrl,
"stargazers_url": stargazersUrl,
"contributors_url": contributorsUrl,
"subscribers_url": subscribersUrl,
"subscription_url": subscriptionUrl,
"commits_url": commitsUrl,
"git_commits_url": gitCommitsUrl,
"comments_url": commentsUrl,
"issue_comment_url": issueCommentUrl,
"contents_url": contentsUrl,
"compare_url": compareUrl,
"merges_url": mergesUrl,
"archive_url": archiveUrl,
"downloads_url": downloadsUrl,
"issues_url": issuesUrl,
"pulls_url": pullsUrl,
"milestones_url": milestonesUrl,
"notifications_url": notificationsUrl,
"labels_url": labelsUrl,
"releases_url": releasesUrl,
"deployments_url": deploymentsUrl,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
"pushed_at": pushedAt.toIso8601String(),
"git_url": gitUrl,
"ssh_url": sshUrl,
"clone_url": cloneUrl,
"svn_url": svnUrl,
"homepage": homepage == null ? null : homepage,
"size": size,
"stargazers_count": stargazersCount,
"watchers_count": watchersCount,
"language": language == null ? null : language,
"has_issues": hasIssues,
"has_projects": hasProjects,
"has_downloads": hasDownloads,
"has_wiki": hasWiki,
"has_pages": hasPages,
"forks_count": forksCount,
"mirror_url": mirrorUrl,
"archived": archived,
"disabled": disabled,
"open_issues_count": openIssuesCount,
"license": license == null ? null : license.toJson(),
"forks": forks,
"open_issues": openIssues,
"watchers": watchers,
"default_branch": defaultBranchValues.reverse[defaultBranch],
"score": score,
};
}
enum DefaultBranch { MASTER }
final defaultBranchValues = EnumValues({"master": DefaultBranch.MASTER});
class License {
String key;
String name;
String spdxId;
String url;
String nodeId;
License({
this.key,
this.name,
this.spdxId,
this.url,
this.nodeId,
});
factory License.fromJson(Map<String, dynamic> json) => License(
key: json["key"],
name: json["name"],
spdxId: json["spdx_id"],
url: json["url"] == null ? null : json["url"],
nodeId: json["node_id"],
);
Map<String, dynamic> toJson() => {
"key": key,
"name": name,
"spdx_id": spdxId,
"url": url == null ? null : url,
"node_id": nodeId,
};
}
class Owner {
String login;
String id;
String nodeId;
String avatarUrl;
String gravatarId;
String url;
String htmlUrl;
String followersUrl;
String followingUrl;
String gistsUrl;
String starredUrl;
String subscriptionsUrl;
String organizationsUrl;
String reposUrl;
String eventsUrl;
String receivedEventsUrl;
Type type;
bool siteAdmin;
Owner({
this.login,
this.id,
this.nodeId,
this.avatarUrl,
this.gravatarId,
this.url,
this.htmlUrl,
this.followersUrl,
this.followingUrl,
this.gistsUrl,
this.starredUrl,
this.subscriptionsUrl,
this.organizationsUrl,
this.reposUrl,
this.eventsUrl,
this.receivedEventsUrl,
this.type,
this.siteAdmin,
});
factory Owner.fromJson(Map<String, dynamic> json) => Owner(
login: json["login"],
id: json["id"].toString(),
nodeId: json["node_id"],
avatarUrl: json["avatar_url"],
gravatarId: json["gravatar_id"],
url: json["url"],
htmlUrl: json["html_url"],
followersUrl: json["followers_url"],
followingUrl: json["following_url"],
gistsUrl: json["gists_url"],
starredUrl: json["starred_url"],
subscriptionsUrl: json["subscriptions_url"],
organizationsUrl: json["organizations_url"],
reposUrl: json["repos_url"],
eventsUrl: json["events_url"],
receivedEventsUrl: json["received_events_url"],
type: typeValues.map[json["type"]],
siteAdmin: json["site_admin"],
);
Map<String, dynamic> toJson() => {
"login": login,
"id": id,
"node_id": nodeId,
"avatar_url": avatarUrl,
"gravatar_id": gravatarId,
"url": url,
"html_url": htmlUrl,
"followers_url": followersUrl,
"following_url": followingUrl,
"gists_url": gistsUrl,
"starred_url": starredUrl,
"subscriptions_url": subscriptionsUrl,
"organizations_url": organizationsUrl,
"repos_url": reposUrl,
"events_url": eventsUrl,
"received_events_url": receivedEventsUrl,
"type": typeValues.reverse[type],
"site_admin": siteAdmin,
};
}
enum Type { USER, ORGANIZATION }
final typeValues =
EnumValues({"Organization": Type.ORGANIZATION, "User": Type.USER});
class EnumValues<T> {
Map<String, T> map;
Map<T, String> reverseMap;
EnumValues(this.map);
Map<T, String> get reverse {
if (reverseMap == null) {
reverseMap = map.map((k, v) => new MapEntry(v, k));
}
return reverseMap;
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
static final String URL = "https://corona.lmao.ninja/countries";
Future _future;
Future<Payload> _fetchData() async {
final response = await http.get(
"https://api.github.com/search/repositories?q=created:%3E2018-10-22&sort=stars&order=desc");
var list = payloadFromJson(response.body);
return list;
}
#override
void initState() {
// TODO: implement initState
super.initState();
_future = _fetchData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: FutureBuilder<Payload>(
future: _future,
builder: (BuildContext context, AsyncSnapshot<Payload> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('Input a URL to start');
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
return Text('');
case ConnectionState.done:
if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.red),
);
} else {
var items = snapshot.data.items;
return ListView.builder(
itemCount: items.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(items[index].name),
leading: CircleAvatar(
backgroundImage:
NetworkImage(items[index].owner.avatarUrl),
),
subtitle: Text(items[index].description),
);
},
);
}
}
}));
}
}

Flutter/Dart Error - NoSuchMethodError: Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'map' with matching arguments

I'm receiving an Error following the Json Deserialisation cookbook
NoSuchMethodError: Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'map' with matching arguments.
Bundle Class
class Bundle {
String resourceType;
String id;
String type;
int total;
List<Link> link;
List<Entry> entry;
Bundle(
{this.resourceType,
this.id,
this.type,
this.total,
this.link,
this.entry});
factory Bundle.fromJson(Map<String, dynamic> json) {
return Bundle(
resourceType : json['resourceType'],
id : json['id'],
type : json['type'],
total : json['total'],
);
}
Code:
try {
await parsePerson(resultString);
} catch (e) {
print('Bundlelist Error: $e');
}
Future<List<Bundle>> parsePerson(String body) async {
List<Bundle> bundleList = [];
try {
final parsed = json.decode(body);
bundleList = parsed.map<Bundle>((json) => Bundle.fromJson(json)).toList;
} catch (e) {
print('FutureError: $e');
}
return bundleList;
}
My Result string (partial): Full json is here.
{"resourceType":"Bundle","id":"f26779b4-5c3c-4c52-83b4-c689516a6a08","type":"searchset","link":[{"relation":"self","url":"https://fhir-open.sandboxcerner.com/dstu2/0b8a0111-e8e6-4c26-a91c-5069cbc6b1ca/Patient?name=b\u0026_count=20"},{"relation":"next","url":"https://fhir-open.sandboxcerner.com/dstu2/0b8a0111-e8e6-4c26-a91c-5069cbc6b1ca/Patient?-pageContext=7018d2bc-6be4-48e1-b8a4-a40f4e98c98c\u0026-pageDirection=NEXT"}],"entry":[{"fullUrl":"https://fhir-open.sandboxcerner.com/dstu2/0b8a0111-e8e6-4c26-a91c-5069cbc6b1ca/Patient/6160015","resource":{"resourceType":"Patient","id":"6160015","meta":{"versionId":"0","lastUpdated":"2019-07-08T20:37:03.000Z"},"text":{"status":"generated","div":"\u003Cdiv\u003E\u003Cp\u003E\u003Cb\u003EPatient\u003C/b\u003E\u003C/p\u003E\u003Cp\u003E\u003Cb\u003EName\u003C/b\u003E: 111d3fcaffb244b2b207c07ffa5a14, bf607a7f1f284e8aa3559d52249bc7\u003C/p\u003E\u003Cp\u003E\u003Cb\u003EDOB\u003C/b\u003E: Mar 15, 1936\u003C/p\u003E\u003Cp\u003E\u003Cb\u003EAdministrative Gend
I've tried various suggestions from here including:
final parsed = jsonDecode(body).cast<Map<String, dynamic>>();
Returns
NoSuchMethodError: Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'cast' with matching arguments.
I'm quite lost as to what to try next.
You need an array, but your response is a map
You json string is too long, I can not paste full code contains your full json
You can copy paste , replace yourjsonstring and run full code below
Your json string contains control character \n and need to replace before parse
You can get all related class in full code
code snippet
String jsonString = '''yourjsonstring''';
String replaced = jsonString.replaceAll('\n',r'\\n');
final payload = payloadFromJson(replaced);
print(payload.link[0].relation);
print(payload.link[0].url);
print(payload.entry[0].resource.address[0].text);
full code
import 'package:flutter/material.dart';
// To parse this JSON data, do
//
// final payload = payloadFromJson(jsonString);
import 'dart:convert';
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
String payloadToJson(Payload data) => json.encode(data.toJson());
class Payload {
String resourceType;
String id;
String type;
List<Link> link;
List<Entry> entry;
Payload({
this.resourceType,
this.id,
this.type,
this.link,
this.entry,
});
factory Payload.fromJson(Map<String, dynamic> json) => Payload(
resourceType: json["resourceType"],
id: json["id"],
type: json["type"],
link: List<Link>.from(json["link"].map((x) => Link.fromJson(x))),
entry: List<Entry>.from(json["entry"].map((x) => Entry.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"resourceType": resourceType,
"id": id,
"type": type,
"link": List<dynamic>.from(link.map((x) => x.toJson())),
"entry": List<dynamic>.from(entry.map((x) => x.toJson())),
};
}
class Entry {
String fullUrl;
Resource resource;
Entry({
this.fullUrl,
this.resource,
});
factory Entry.fromJson(Map<String, dynamic> json) => Entry(
fullUrl: json["fullUrl"],
resource: Resource.fromJson(json["resource"]),
);
Map<String, dynamic> toJson() => {
"fullUrl": fullUrl,
"resource": resource.toJson(),
};
}
class Resource {
ResourceType resourceType;
String id;
Meta meta;
TextClass text;
List<Identifier> identifier;
bool active;
List<Name> name;
List<Telecom> telecom;
Gender gender;
DateTime birthDate;
List<Address> address;
Resource({
this.resourceType,
this.id,
this.meta,
this.text,
this.identifier,
this.active,
this.name,
this.telecom,
this.gender,
this.birthDate,
this.address,
});
factory Resource.fromJson(Map<String, dynamic> json) => Resource(
resourceType: resourceTypeValues.map[json["resourceType"]],
id: json["id"],
meta: Meta.fromJson(json["meta"]),
text: TextClass.fromJson(json["text"]),
identifier: List<Identifier>.from(json["identifier"].map((x) => Identifier.fromJson(x))),
active: json["active"],
name: List<Name>.from(json["name"].map((x) => Name.fromJson(x))),
telecom: List<Telecom>.from(json["telecom"].map((x) => Telecom.fromJson(x))),
gender: genderValues.map[json["gender"]],
birthDate: DateTime.parse(json["birthDate"]),
address: List<Address>.from(json["address"].map((x) => Address.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"resourceType": resourceTypeValues.reverse[resourceType],
"id": id,
"meta": meta.toJson(),
"text": text.toJson(),
"identifier": List<dynamic>.from(identifier.map((x) => x.toJson())),
"active": active,
"name": List<dynamic>.from(name.map((x) => x.toJson())),
"telecom": List<dynamic>.from(telecom.map((x) => x.toJson())),
"gender": genderValues.reverse[gender],
"birthDate": "${birthDate.year.toString().padLeft(4, '0')}-${birthDate.month.toString().padLeft(2, '0')}-${birthDate.day.toString().padLeft(2, '0')}",
"address": List<dynamic>.from(address.map((x) => x.toJson())),
};
}
class Address {
AddressUse use;
String text;
List<String> line;
String city;
String state;
String postalCode;
String country;
AddressPeriod period;
Address({
this.use,
this.text,
this.line,
this.city,
this.state,
this.postalCode,
this.country,
this.period,
});
factory Address.fromJson(Map<String, dynamic> json) => Address(
use: addressUseValues.map[json["use"]],
text: json["text"],
line: List<String>.from(json["line"].map((x) => x)),
city: json["city"],
state: json["state"],
postalCode: json["postalCode"],
country: json["country"],
period: json["period"] == null ? null : AddressPeriod.fromJson(json["period"]),
);
Map<String, dynamic> toJson() => {
"use": addressUseValues.reverse[use],
"text": text,
"line": List<dynamic>.from(line.map((x) => x)),
"city": city,
"state": state,
"postalCode": postalCode,
"country": country,
"period": period == null ? null : period.toJson(),
};
}
class AddressPeriod {
DateTime start;
AddressPeriod({
this.start,
});
factory AddressPeriod.fromJson(Map<String, dynamic> json) => AddressPeriod(
start: DateTime.parse(json["start"]),
);
Map<String, dynamic> toJson() => {
"start": start.toIso8601String(),
};
}
enum AddressUse { HOME, WORK, MOBILE }
final addressUseValues = EnumValues({
"home": AddressUse.HOME,
"mobile": AddressUse.MOBILE,
"work": AddressUse.WORK
});
enum Gender { UNKNOWN, OTHER }
final genderValues = EnumValues({
"other": Gender.OTHER,
"unknown": Gender.UNKNOWN
});
class Identifier {
IdentifierUse use;
Type type;
IdentifierSystem system;
String identifierValue;
Value value;
AddressPeriod period;
Identifier({
this.use,
this.type,
this.system,
this.identifierValue,
this.value,
this.period,
});
factory Identifier.fromJson(Map<String, dynamic> json) => Identifier(
use: identifierUseValues.map[json["use"]],
type: Type.fromJson(json["type"]),
system: identifierSystemValues.map[json["system"]],
identifierValue: json["value"],
value: Value.fromJson(json["_value"]),
period: AddressPeriod.fromJson(json["period"]),
);
Map<String, dynamic> toJson() => {
"use": identifierUseValues.reverse[use],
"type": type.toJson(),
"system": identifierSystemValues.reverse[system],
"value": identifierValue,
"_value": value.toJson(),
"period": period.toJson(),
};
}
enum IdentifierSystem { URN_OID_2168401113883378700, URN_OID_111111, URN_OID_21684011138833421000110000112 }
final identifierSystemValues = EnumValues({
"urn:oid:1.1.1.1.1.1": IdentifierSystem.URN_OID_111111,
"urn:oid:2.16.840.1.113883.3.42.10001.100001.12": IdentifierSystem.URN_OID_21684011138833421000110000112,
"urn:oid:2.16.840.1.113883.3.787.0.0": IdentifierSystem.URN_OID_2168401113883378700
});
class Type {
List<Coding> coding;
TextEnum text;
Type({
this.coding,
this.text,
});
factory Type.fromJson(Map<String, dynamic> json) => Type(
coding: json["coding"] == null ? null : List<Coding>.from(json["coding"].map((x) => Coding.fromJson(x))),
text: textEnumValues.map[json["text"]],
);
Map<String, dynamic> toJson() => {
"coding": coding == null ? null : List<dynamic>.from(coding.map((x) => x.toJson())),
"text": textEnumValues.reverse[text],
};
}
class Coding {
String system;
Code code;
Display display;
bool userSelected;
Coding({
this.system,
this.code,
this.display,
this.userSelected,
});
factory Coding.fromJson(Map<String, dynamic> json) => Coding(
system: json["system"],
code: codeValues.map[json["code"]],
display: displayValues.map[json["display"]],
userSelected: json["userSelected"],
);
Map<String, dynamic> toJson() => {
"system": system,
"code": codeValues.reverse[code],
"display": displayValues.reverse[display],
"userSelected": userSelected,
};
}
enum Code { MR }
final codeValues = EnumValues({
"MR": Code.MR
});
enum Display { MEDICAL_RECORD_NUMBER }
final displayValues = EnumValues({
"Medical record number": Display.MEDICAL_RECORD_NUMBER
});
enum TextEnum { COMMUNITY_MEDICAL_RECORD_NUMBER, MRN, MILITARY_ID }
final textEnumValues = EnumValues({
"Community Medical Record Number": TextEnum.COMMUNITY_MEDICAL_RECORD_NUMBER,
"Military Id": TextEnum.MILITARY_ID,
"MRN": TextEnum.MRN
});
enum IdentifierUse { USUAL }
final identifierUseValues = EnumValues({
"usual": IdentifierUse.USUAL
});
class Value {
List<Extension> extension;
Value({
this.extension,
});
factory Value.fromJson(Map<String, dynamic> json) => Value(
extension: List<Extension>.from(json["extension"].map((x) => Extension.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"extension": List<dynamic>.from(extension.map((x) => x.toJson())),
};
}
class Extension {
String url;
String valueString;
Extension({
this.url,
this.valueString,
});
factory Extension.fromJson(Map<String, dynamic> json) => Extension(
url: json["url"],
valueString: json["valueString"],
);
Map<String, dynamic> toJson() => {
"url": url,
"valueString": valueString,
};
}
class Meta {
String versionId;
DateTime lastUpdated;
Meta({
this.versionId,
this.lastUpdated,
});
factory Meta.fromJson(Map<String, dynamic> json) => Meta(
versionId: json["versionId"],
lastUpdated: DateTime.parse(json["lastUpdated"]),
);
Map<String, dynamic> toJson() => {
"versionId": versionId,
"lastUpdated": lastUpdated.toIso8601String(),
};
}
class Name {
NameUse use;
String text;
List<String> family;
List<String> given;
List<String> prefix;
NamePeriod period;
List<String> suffix;
Name({
this.use,
this.text,
this.family,
this.given,
this.prefix,
this.period,
this.suffix,
});
factory Name.fromJson(Map<String, dynamic> json) => Name(
use: nameUseValues.map[json["use"]],
text: json["text"],
family: List<String>.from(json["family"].map((x) => x)),
given: List<String>.from(json["given"].map((x) => x)),
prefix: json["prefix"] == null ? null : List<String>.from(json["prefix"].map((x) => x)),
period: json["period"] == null ? null : NamePeriod.fromJson(json["period"]),
suffix: json["suffix"] == null ? null : List<String>.from(json["suffix"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"use": nameUseValues.reverse[use],
"text": text,
"family": List<dynamic>.from(family.map((x) => x)),
"given": List<dynamic>.from(given.map((x) => x)),
"prefix": prefix == null ? null : List<dynamic>.from(prefix.map((x) => x)),
"period": period == null ? null : period.toJson(),
"suffix": suffix == null ? null : List<dynamic>.from(suffix.map((x) => x)),
};
}
class NamePeriod {
DateTime start;
DateTime end;
NamePeriod({
this.start,
this.end,
});
factory NamePeriod.fromJson(Map<String, dynamic> json) => NamePeriod(
start: json["start"] == null ? null : DateTime.parse(json["start"]),
end: json["end"] == null ? null : DateTime.parse(json["end"]),
);
Map<String, dynamic> toJson() => {
"start": start == null ? null : start.toIso8601String(),
"end": end == null ? null : end.toIso8601String(),
};
}
enum NameUse { OFFICIAL, OLD }
final nameUseValues = EnumValues({
"official": NameUse.OFFICIAL,
"old": NameUse.OLD
});
enum ResourceType { PATIENT }
final resourceTypeValues = EnumValues({
"Patient": ResourceType.PATIENT
});
class Telecom {
TelecomSystem system;
ValueEnum value;
AddressUse use;
AddressPeriod period;
Telecom({
this.system,
this.value,
this.use,
this.period,
});
factory Telecom.fromJson(Map<String, dynamic> json) => Telecom(
system: telecomSystemValues.map[json["system"]],
value: valueEnumValues.map[json["value"]],
use: addressUseValues.map[json["use"]],
period: json["period"] == null ? null : AddressPeriod.fromJson(json["period"]),
);
Map<String, dynamic> toJson() => {
"system": telecomSystemValues.reverse[system],
"value": valueEnumValues.reverse[value],
"use": addressUseValues.reverse[use],
"period": period == null ? null : period.toJson(),
};
}
enum TelecomSystem { PHONE, EMAIL }
final telecomSystemValues = EnumValues({
"email": TelecomSystem.EMAIL,
"phone": TelecomSystem.PHONE
});
enum ValueEnum { THE_3213213213, NAME_FAKEMAIL_COM, THE_8888888888 }
final valueEnumValues = EnumValues({
"name#fakemail.com": ValueEnum.NAME_FAKEMAIL_COM,
"321-321-3213": ValueEnum.THE_3213213213,
"888-888-8888": ValueEnum.THE_8888888888
});
class TextClass {
Status status;
String div;
TextClass({
this.status,
this.div,
});
factory TextClass.fromJson(Map<String, dynamic> json) => TextClass(
status: statusValues.map[json["status"]],
div: json["div"],
);
Map<String, dynamic> toJson() => {
"status": statusValues.reverse[status],
"div": div,
};
}
enum Status { GENERATED }
final statusValues = EnumValues({
"generated": Status.GENERATED
});
class Link {
String relation;
String url;
Link({
this.relation,
this.url,
});
factory Link.fromJson(Map<String, dynamic> json) => Link(
relation: json["relation"],
url: json["url"],
);
Map<String, dynamic> toJson() => {
"relation": relation,
"url": url,
};
}
class EnumValues<T> {
Map<String, T> map;
Map<T, String> reverseMap;
EnumValues(this.map);
Map<T, String> get reverse {
if (reverseMap == null) {
reverseMap = map.map((k, v) => new MapEntry(v, k));
}
return reverseMap;
}
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
String jsonString = '''yourjsonstring''';
//String jsonString = '''{"newLine": "here is a \n newline \u003E \u0026 \u003C aaa"}''';
void _incrementCounter() {
String replaced = jsonString.replaceAll('\n',r'\\n');
final payload = payloadFromJson(replaced);
print(payload.link[0].relation);
print(payload.link[0].url);
print(payload.entry[0].resource.address[0].text);
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}