how to use for loop in flutter - flutter

i want to use for loop i need "photoThumbnailImagePath" array but i am not able to work on it...! i am trying to get array index of image path but i getting only one image.....! my value is not printing ! i gave u my code and my json data...! plz show me how it works how should i print my image value
if (response.statusCode == 200) {
var jsonResponse = json.decode(response.body);
print("laavvvvvvvvv :" + jsonResponse.toString());
var azim = List<FolderList>.from(jsonResponse["FolderList"].map((x) => FolderList.fromJson(x)));
// ignore: unnecessary_statements
print("printing");
for (final cam in azim){
print("photoThumbnailImagePath:" + cam.photoList[0].photoThumbnailImagePath.toString()); //i am getting here first image only i want all alisting array how
Photlistinng = [cam.photoList[0].photoThumbnailImagePath];
print("Photlistinng : " + Photlistinng.toString());
};
return AllPhotoListing.fromJson(json.decode(response.body));
} else {
// If the server did not return a 201 CREATED response,
// then throw an exception.
throw Exception('Failed to load data');
}
this my my code when api succesful then i use for loop but something wrong with my code so plz check
here is my json data converter
import 'dart:convert';
AllPhotoListing allPhotoListingFromJson(String str) => AllPhotoListing.fromJson(json.decode(str));
String allPhotoListingToJson(AllPhotoListing data) => json.encode(data.toJson());
class AllPhotoListing {
AllPhotoListing({
this.successCode,
this.successMessage,
this.totalPhotos,
this.totalLikes,
this.totalComments,
this.totalShared,
this.totalSelectedPhotosForAlbum,
this.watermarkType,
this.watermarkLogo,
this.watermarkText,
this.watermarkFont,
this.watermarkFontColor,
this.watermarkScaleHeight,
this.watermarkScaleWidth,
this.watermarkOpacity,
this.watermarkFontSize,
this.watermarkPlacement,
this.folderList,
});
String successCode;
String successMessage;
int totalPhotos;
int totalLikes;
int totalComments;
int totalShared;
int totalSelectedPhotosForAlbum;
String watermarkType;
String watermarkLogo;
String watermarkText;
String watermarkFont;
String watermarkFontColor;
int watermarkScaleHeight;
int watermarkScaleWidth;
double watermarkOpacity;
int watermarkFontSize;
String watermarkPlacement;
List<FolderList> folderList;
factory AllPhotoListing.fromJson(Map<String, dynamic> json) => AllPhotoListing(
successCode: json["SuccessCode"],
successMessage: json["SuccessMessage"],
totalPhotos: json["TotalPhotos"],
totalLikes: json["TotalLikes"],
totalComments: json["TotalComments"],
totalShared: json["TotalShared"],
totalSelectedPhotosForAlbum: json["TotalSelectedPhotosForAlbum"],
watermarkType: json["WatermarkType"],
watermarkLogo: json["WatermarkLogo"],
watermarkText: json["WatermarkText"],
watermarkFont: json["WatermarkFont"],
watermarkFontColor: json["WatermarkFontColor"],
watermarkScaleHeight: json["WatermarkScaleHeight"],
watermarkScaleWidth: json["WatermarkScaleWidth"],
watermarkOpacity: json["WatermarkOpacity"].toDouble(),
watermarkFontSize: json["WatermarkFontSize"],
watermarkPlacement: json["WatermarkPlacement"],
folderList: List<FolderList>.from(json["FolderList"].map((x) => FolderList.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"SuccessCode": successCode,
"SuccessMessage": successMessage,
"TotalPhotos": totalPhotos,
"TotalLikes": totalLikes,
"TotalComments": totalComments,
"TotalShared": totalShared,
"TotalSelectedPhotosForAlbum": totalSelectedPhotosForAlbum,
"WatermarkType": watermarkType,
"WatermarkLogo": watermarkLogo,
"WatermarkText": watermarkText,
"WatermarkFont": watermarkFont,
"WatermarkFontColor": watermarkFontColor,
"WatermarkScaleHeight": watermarkScaleHeight,
"WatermarkScaleWidth": watermarkScaleWidth,
"WatermarkOpacity": watermarkOpacity,
"WatermarkFontSize": watermarkFontSize,
"WatermarkPlacement": watermarkPlacement,
"FolderList": List<dynamic>.from(folderList.map((x) => x.toJson())),
};
}
class FolderList {
FolderList({
this.folderId,
this.title,
this.totalCount,
this.photoList,
});
int folderId;
String title;
int totalCount;
List<PhotoList> photoList;
factory FolderList.fromJson(Map<String, dynamic> json) => FolderList(
folderId: json["FolderId"],
title: json["Title"],
totalCount: json["TotalCount"],
photoList: List<PhotoList>.from(json["PhotoList"].map((x) => PhotoList.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"FolderId": folderId,
"Title": title,
"TotalCount": totalCount,
"PhotoList": List<dynamic>.from(photoList.map((x) => x.toJson())),
};
}
class PhotoList {
PhotoList({
this.photoId,
this.photoMainImagePath,
this.photoThumbnailImagePath, // i need this array in my api call
this.photoPreviewImagePath,
this.isSelectedPhoto,
this.isLikedPhoto,
this.photoSelectedCustomers,
this.photoSelectedPhotographerProfile,
});
int photoId;
String photoMainImagePath;
String photoThumbnailImagePath;
String photoPreviewImagePath;
int isSelectedPhoto;
int isLikedPhoto;
List<PhotoSelectedCustomer> photoSelectedCustomers;
String photoSelectedPhotographerProfile;
factory PhotoList.fromJson(Map<String, dynamic> json) => PhotoList(
photoId: json["PhotoId"],
photoMainImagePath: json["PhotoMainImagePath"],
photoThumbnailImagePath: json["PhotoThumbnailImagePath"],
photoPreviewImagePath: json["PhotoPreviewImagePath"],
isSelectedPhoto: json["IsSelectedPhoto"],
isLikedPhoto: json["IsLikedPhoto"],
photoSelectedCustomers: List<PhotoSelectedCustomer>.from(json["PhotoSelectedCustomers"].map((x) =>
PhotoSelectedCustomer.fromJson(x))),
photoSelectedPhotographerProfile: json["PhotoSelectedPhotographerProfile"],
);
Map<String, dynamic> toJson() => {
"PhotoId": photoId,
"PhotoMainImagePath": photoMainImagePath,
"PhotoThumbnailImagePath": photoThumbnailImagePath,
"PhotoPreviewImagePath": photoPreviewImagePath,
"IsSelectedPhoto": isSelectedPhoto,
"IsLikedPhoto": isLikedPhoto,
"PhotoSelectedCustomers": List<dynamic>.from(photoSelectedCustomers.map((x) => x.toJson())),
"PhotoSelectedPhotographerProfile": photoSelectedPhotographerProfile,
};
}
class PhotoSelectedCustomer {
PhotoSelectedCustomer({
this.profilePicture,
});
String profilePicture;
factory PhotoSelectedCustomer.fromJson(Map<String, dynamic> json) => PhotoSelectedCustomer(
profilePicture: json["ProfilePicture"],
);
Map<String, dynamic> toJson() => {
"ProfilePicture": profilePicture,
};
}

you can try this :
for(int i=0; i<azim.length; i++){
//print here
}

Related

Get data for class from JSON - Flutter

I have a class "DilemmData" whose variables are loaded with data like this:
if (prefs.containsKey('dilemms')) {
MyApp.dilemmList = DilemmData.decode(prefs.getString('dilemms')!);
}
Here is the class:
class DilemmData {
double percent;
final String title;
final String date;
final List<DilemmItemData> plus = [];
final List<DilemmItemData> minus = [];
DilemmData({
plus,
minus,
this.percent = 0,
this.title = '',
this.date = '',
});
static Map<String, dynamic> toJson(DilemmData dilemm) => {
'percent': dilemm.percent,
'title': dilemm.title,
'date': dilemm.date,
'plus': dilemm.plus.map((e) => e.toJson()).toList(),
'minus': dilemm.minus.map((e) => e.toJson()).toList(),
};
factory DilemmData.fromJson(Map<String, dynamic> json) {
print('BOBA: ${json['plus']}');
return DilemmData(
plus: json['plus'],
minus: json['minus'],
percent: json['percent'],
title: json['title'],
date: json['date'],
);
}
static String encode(List<DilemmData> dilemm) => json.encode(
dilemm
.map<Map<String, dynamic>>((dil) => DilemmData.toJson(dil))
.toList(),
);
static List<DilemmData> decode(String dilemm) =>
(json.decode(dilemm) as List<dynamic>)
.map<DilemmData>((dil) => DilemmData.fromJson(dil))
.toList();
}
class DilemmItemData {
final int importance;
final String argument;
DilemmItemData({this.importance = 0, this.argument = ''});
Map<String, dynamic> toJson() {
return {
'importance': importance,
'argument': argument,
};
}
factory DilemmItemData.fromJson(Map<String, dynamic> json) {
return DilemmItemData(
importance: json['importance'], argument: json['argument']);
}
static List<DilemmItemData> decode(String item) =>
(json.decode(item) as List<dynamic>)
.map<DilemmItemData>((dil) => DilemmItemData.fromJson(dil))
.toList();
}
But the plus and minus variables are always empty. Does anyone know how to fix this?
The following code snippet would do the trick. Converting a DilemmItemData from JSON was missing.
factory DilemmData.fromJson(Map<String, dynamic> json) {
return DilemmData(
plus: (json['plus'] as List)
.map((json) => DilemmItemData.fromJson(json))
.toList(),
minus: (json['minus'] as List)
.map((json) => DilemmItemData.fromJson(json))
.toList(),
percent: json['percent'],
title: json['title'],
date: json['date'],
);
}

Conversion error from object to json and back in flutter

I am trying to convert a list of objects as a json string in shared preferences.
Object class
SuggestionModel suggestionModelFromJson(String str) =>
SuggestionModel.fromJson(json.decode(str));
String suggestionModelToJson(SuggestionModel data) =>
json.encode(data.toJson());
class SuggestionModel {
SuggestionModel({
this.category,
this.icon,
this.subs,
});
eCategory? category;
IconData? icon;
List<Sub>? subs;
factory SuggestionModel.fromJson(Map<String, dynamic> json) =>
SuggestionModel(
category: json["category"],
icon: json["icon"],
subs: List<Sub>.from(json["subs"].map((x) => Sub.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"category": category,
"icon": icon,
"subs": List<dynamic>.from(subs!.map((x) => x.toJson())),
};
}
class Sub {
Sub({
this.subCategory,
this.values,
});
String? subCategory;
List<Value>? values;
factory Sub.fromJson(Map<String, dynamic> json) => Sub(
subCategory: json["sub_category"],
values: List<Value>.from(json["values"].map((x) => Value.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"sub_category": subCategory,
"values": List<dynamic>.from(values!.map((x) => x.toJson())),
};
}
class Value {
Value({
this.subName,
this.selected,
});
String? subName;
bool? selected;
factory Value.fromJson(Map<String, dynamic> json) => Value(
subName: json["sub_name"],
selected: json["selected"],
);
Map<String, dynamic> toJson() => {
"sub_name": subName,
"selected": selected,
};
}
When I try to do
List<SuggestionModel> list;
String encodedData = jsonEncode(list);
it gives me an error
Converting object to an encodable object failed: Instance of 'SuggestionModel'
Im not following where the exact issue comes from. tried debugging and still no luck
How can I rectify this?
Update. I've changed the enum to a String and removed the IconData field. And the above issue had resolved.
Now when I try to get the saved Json string and convert that back to list of objects. I get an error
Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<SuggestionModel>'
at this line
var t = await _dataManager.getSelectedList(s);
var addedObj = json.decode(json.decode(t!));
//here...
var list = addedObj.map((e) => SuggestionModel.fromJson(e)).toList();
Try this:
String encodedData = jsonEncode(list.map((e) => e.toJson()).toList());
So the first thing was to update the enum property of Model class to String and remove IconData.
Then for the second issue.
update the decoding function like
List<SuggestionModel> list =
addedObj.map((e) => SuggestionModel.fromJson(e)).toList();

Flutter abstract class with factory methods

I am new to working with dart/flutter!
Tell me pls how to correctly implement an abstract class in which a factory method is needed
I have a large number of models with the same methods (factory Model.fromJsom, listFromJson)! I want to make an interface for such models, but I don’t understand how to make a factory method and a static in abstract class
Examples
class Post extends Equatable {
Post({
required this.id,
required this.title,
});
final int id;
final String title;
#override
List<Object> get props => [
id,
title,
];
factory Post.fromJson(dynamic json) {
return Post(
id: json['id'] as int,
title: json['name'] as String,
);
}
Map<String, dynamic> toJson() {
return {
'id': id,
'title': title,
};
}
static List<Post> listFromJson(List<dynamic> json) {
return json.map((value) => Post.fromJson(value)).toList();
}
#override
String toString() {
return '''Post { id: $id, title: $title }''';
}
}
I find it's always a headache to work with JSON array directly. The solution I find is to wrap the List inside another class, in this case ListPost as follows:
class Post {
final int id;
final String title;
Post({required this.id, required this.title});
factory Post.fromJson(Map<String, dynamic> json) => Post(
id: json['id'] as int,
title: json['title'] as String,
);
Map<String, dynamic> toJson() => <String, dynamic>{
'id': id,
'title': title,
};
}
class ListPost {
final List<Post> list;
ListPost({required this.list});
factory ListPost.fromJson(Map<String, dynamic> json) => ListPost(
list: (json['list'] as List<dynamic>)
.map((e) => Post.fromJson(e as Map<String, dynamic>))
.toList(),
);
Map<String, dynamic> toJson() => <String, dynamic>{
'list': list,
};
}
And the example JSON is like this:
{
"list": [
{"id": 1, "title": "TITLE_1"},
{"id": 2, "title": "TITLE_2"}
]
}
I hope this is workable for you.
You can simply use this website it will convert your json to a dart file and you can easily call the methods .fromJson and .toJson to convert from json to entity and vice versa quicktype website
JSON source
{
"greeting": "Welcome to quicktype!",
"instructions": [
"Type or paste JSON here",
"Or choose a sample above",
"quicktype will generate code in your",
"chosen language to parse the sample data"
]
}
Dart file
import 'dart:convert';
Welcome welcomeFromJson(String str) => Welcome.fromJson(json.decode(str));
String welcomeToJson(Welcome data) => json.encode(data.toJson());
class Welcome {
Welcome({
this.greeting,
this.instructions,
});
String greeting;
List<String> instructions;
factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
greeting: json["greeting"] == null ? null : json["greeting"],
instructions: json["instructions"] == null ? null : List<String>.from(json["instructions"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"greeting": greeting == null ? null : greeting,
"instructions": instructions == null ? null : List<dynamic>.from(instructions.map((x) => x)),
};
}

A value of type 'Resut' can't be returned from function'fetchPromotions' because it has a return type of Future<List<Promotions>>

I am fetching some data from an API, which returns a Json array, promotions_model.dart does all the parsing, but this error is showing up.
Error--
A value of type 'Result' can't be returned from function 'fetchPromotions' because it has a return type of 'Future<List>'.
can someone please tell me what i am doing wrong here. thanks
**promotions_model.dart**
import 'dart:convert';
Result resultFromJson(String str) => Result.fromJson(json.decode(str));
String resultToJson(Result data) => json.encode(data.toJson());
class Result {
Result({
this.code,
this.result,
});
final int code;
final List<Promotions> result;
factory Result.fromJson(Map<String, dynamic> json) => Result(
code: json["Code"],
result: List<Promotions>.from(
json["Result"].map((x) => Promotions.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"Code": code,
"Result": List<dynamic>.from(result.map((x) => x.toJson())),
};
}
class Promotions {
Promotions({
this.id,
this.title,
this.description,
this.image,
});
final String id;
final String title;
final String description;
final String image;
factory Promotions.fromJson(Map<String, dynamic> json) => Promotions(
id: json["id"],
title: json["title"],
description: json["description"],
image: json["image"],
);
Map<String, dynamic> toJson() => {
"id": id,
"title": title,
"description": description,
"image": image,
};
}
**promotion-api.dart**
import 'dart:async';
import 'package:http/http.dart' as http;
import 'package:project/models/promotions_model.dart';
const key = {
'APP-X-RESTAPI-KEY': "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
};
const API = 'http://111.111.11.1/project';
Future<List<Promotions>> fetchPromotions() async {
final response = await http.get(API + '/promotion/all', headers: key);
if (response.statusCode == 200) {
return resultFromJson(response.body); // This line is causing the error
} else {
print(response.statusCode);
}
}
The Error says it clearly. It needs Result as the return type.
You can something like this,
Result fetchPromotions() async {
final response = await http.get(API + '/promotion/all', headers: key);
Result result = null;
if (response.statusCode == 200) {
result = resultFromJson(response.body); // This line is causing the error
} else {
print(response.statusCode);
}
return result;
}
Hope you got an idea.
return resultFromJson(response.body);
This line returns a Result, not a List<Promotion>.

How create a interface (class) in Dart for an nested Map

In my Flutter app I receive notifications with a custom payload, like:
{ notification:
{
title: Test,
body: AAAA
},
data:
{
productId: Axe,
page: Products,
click_action: FLUTTER_NOTIFICATION_CLICK
}
}
Everything works well. I also can handle the payload of the notification by access it through:
message['data']['page']
But I rather would like to use an Interface/Class to name the data by key, for example:
message.data.page and message.data.productId
So I tried:
class NotificationMessage {
Map notification;
Map data;
NotificationMessage(this.notification, this.data);
}
...
NotificationMessage _message = message; // Assigning the payload to the final
...
This where I get stuck: here I got the error: A value of type 'Map<dynamic, dynamic>' can't be assigned to a variable of type 'NotificationMessage'.
My class isn't finished yet, but how to continue?
I' aware of json_serializable, but before any tooling, I would like to understand it fully.
First, you need to build the two models for notification and data as follows
class DataMessage {
final String productId;
final String page;
final String click_action;
DataMessage(this.productId, this.page, this.click_action);
factory DataMessage.fromJson(Map<dynamic, dynamic> json) {
return DataMessage(
json['productId'] as String,
json['page'] as String,
json['click_action'] as String,
);
}
}
class NotificationMessage {
final String title;
final String body;
NotificationMessage(this.title, this.body);
factory NotificationMessage.fromJson(Map<dynamic, dynamic> json) {
return NotificationMessage(
json['title'] as String,
json['body'] as String,
);
}
}
The factory method convert map types into model classes.
Then you have to build a model for the response message as follows
class Message {
final NotificationMessage notification;
final DataMessage data;
Message(this.notification, this.data);
factory Message.fromJson(Map<dynamic, dynamic> json) {
final Map<dynamic, dynamic> mapNotification = json['notification'];
final Map<dynamic, dynamic> mapData = json['data'];
final dataModel = DataMessage.fromJson(mapData);
final notificationModel = NotificationMessage.fromJson(mapNotification);
return Message(
notificationModel as NotificationMessage,
dataModel as DataMessage,
);
}
}
Note that the factory method allows you to convert the maps for each model to a class model
So you can define your response as a class
Map<dynamic, dynamic> messageResponse = {
'notification': {'title': 'Test', 'body': 'AAAA'},
'data': {
'productId': 'Axe',
'page': 'Products',
'click_action': 'FLUTTER_NOTIFICATION_CLICK'
}
};
final Message message = Message.fromJson(messageResponse);
print(message.data.productId);
print(message.data.page);
print(message.data.click_action);
print(message.notification.title);
print(message.notification.body);
Hope that can help you
Instance of the json object. this way you can use a map for any instance without modifying the class
{ "notification":
{
"title": "Test",
"body": "AAAA"
},
"data":
{
"productId": "Axe",
"page": "Products",
"click_action": "FLUTTER_NOTIFICATION_CLICK"
}
}
Class looks like;
class NotificationMessage {
NotificationMessage({
this.notification,
this.data,
});
final Notification notification;
final Data data;
factory NotificationMessage.fromJson(Map<String, dynamic> json) => NotificationMessage(
notification: Notification.fromJson(json["notification"]),
data: Data.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"notification": notification.toJson(),
"data": data.toJson(),
};
}
class Data {
Data({
this.productId,
this.page,
this.clickAction,
});
final String productId;
final String page;
final String clickAction;
factory Data.fromJson(Map<String, dynamic> json) => Data(
productId: json["productId"],
page: json["page"],
clickAction: json["click_action"],
);
Map<String, dynamic> toJson() => {
"productId": productId,
"page": page,
"click_action": clickAction,
};
}
class Notification {
Notification({
this.title,
this.body,
});
final String title;
final String body;
factory Notification.fromJson(Map<String, dynamic> json) => Notification(
title: json["title"],
body: json["body"],
);
Map<String, dynamic> toJson() => {
"title": title,
"body": body,
};
}
A function to build as
Future<NotificationMessage> getNotf() {
var parsedJson = json.decode(//your received object);
return NotificationMessage.fromJson(parsedJson);
}
Now you can receive this in a builder such as
_futureNotifications =Future<NotificationMessage>
_futureNotifications = getNotf(); //this is a function and can be used after a gesture or initState
FutureBuilder<NotificationMessage>(
future: _futureNotifications,
builder: (context, snapshot) {
}