How to select the desired elements in a list in Dart, and change the data of this element - flutter

I have an array with such data (more data in reality)
[
{
serviceid: "979cf8e6",
amount: 1,
price: 0,
materialsPrice: 100,
enable: true,
chenge: true
},
{
serviceid: "979cf812",
amount: 1,
price: 15.5,
materialsPrice: 0,
enable: true,
chenge: false
}
]
My goal is to change "enable" to the desired status in the selected element of the array. For this I will use a block. That is, if when I click on the event, I transfer (false and "979cf8e6") . Then the required element should be found (service = 979cf8e6). And this element should have enable on false. I tried to start something, but it didn't work. Maybe someone knows how to do it?))
on<OnChangeStatusListItemClick>((event, emit) async {
var serviceId = event.serviceId;//(my serviceId here)
var paymentStatus = event.status;//(my new status here)
var paymentDetails = state.listVariant; //(my list here)
PaymentDetailsModel? selected;
paymentDetails = paymentDetails.map((paymentDetailsOne) {
paymentDetailsOne.serviceid == serviceId;
var selectedPaymentDetails = paymentDetailsOne.copyWith(enable: paymentStatus);
return selectedPaymentDetails;
}).toList();
emit(state.copyWith(listVariant: paymentDetails));
});
My PaymentDetailsModel model (this model is used in listVariant)
#freezed
class PaymentDetailsModel with _$PaymentDetailsModel {
#JsonSerializable(fieldRename: FieldRename.none, explicitToJson: true)
const factory PaymentDetailsModel({
required String serviceid,
required double? price,
required int? minmal,
required int amount,
required bool enable,
required bool chenge,
}) = _PaymentDetailsModel;
factory PaymentDetailsModel.fromJson(Map<String, dynamic> json) =>
_$PaymentDetailsModelFromJson(json);
}

I think maybe you miss if else check in your map function, not pretty sure, but you can try :
on<OnChangeStatusListItemClick>((event, emit) async {
final serviceId = event.serviceId;//(my serviceId here)
final paymentStatus = event.status;//(my new status here)
final paymentDetails = state.listVariant.map((paymentDetailsOne) {
if ( paymentDetailsOne.serviceid == serviceId) {
return paymentDetailsOne.copyWith(enable: paymentStatus);
} else {
return paymentDetailsOne;
}
}).toList();
emit(state.copyWith(listVariant: paymentDetails));
});

Related

how to filter data based on tag in flutter?

I am creating a screen where need to filter data based on category types and transaction type.
Its working fine but it results null when filter list is empty, I can manage with some logically tricks but it will be lengthy coding..
is there any other better way to filter data properly even if filter tag is empty and
should display all records based on transaction type
like
transactiontype='Expense'
filtertags=[]
result:
it should display all expense transactions
transactiontype='Expense'
filtertags=['Food']
result:
it should display all expense transactions of Food
class TransactionModel {
String category;
double amount;
bool isExpense;
TransactionModel(
{required this.category, required this.amount, this.isExpense = true});
String printData() {
return 'Category:' +
category +
' Amount: ' +
amount.toString() +
'isExpense:' +
isExpense.toString();
}
}
List<String> _filtertags = ['Food'];// if this list is empty it should show all posible records
String transactiontype = 'Expense';
List<TransactionModel> transactions = [
TransactionModel(
category: 'Shopping',
amount: 4300,
),
TransactionModel(category: 'Food', amount: 2200,isExpense: true),
TransactionModel(category: 'Loan', amount: 400, isExpense: false),
TransactionModel(category: 'Food', amount: 300,isExpense: false),
TransactionModel(category: 'Other', amount: 100,isExpense: true),
];
void main() {
var resultdata = transactiontype == 'All'
? transactions
.where((element) => _filtertags.contains(element.category))
.toList()
: transactiontype == 'Expense'
? transactions
.where((element) =>
_filtertags.contains(element.category) &&
element.isExpense == true)
.toList()
: transactions
.where((element) =>
_filtertags.contains(element.category) &&
element.isExpense == false)
.toList();
for (var x in resultdata) {
print(x.printData());
}
}
You can simplify like
var result = [];
if (transactionType == 'All' || transactionType.isEmpty) {
result = transactions.toList();
} else {
bool isExpense = transactionType == 'Expense';
//add more filter when needed and comare with model class
result = transactions
.where((element) =>
_filterTags.contains(element.category) &&
element.isExpense == isExpense)
.toList();
}
for (var x in result) {
print(x.toString());
}
});

How to create a model for pictures from Unsplash?

I need to use the Unsplash API to display a list of pictures that come to me, the title and the author. The problem is that I do not understand how to create a model for converting JSON that comes to me so that I can get the picture, author and title. JSON has nested elements and I don't understand how to do it. How can i do this?
My JSON for one picture:
{
"id":"RBo6ayiFND0",
"created_at":"2022-07-08T13:04:40-04:00",
"updated_at":"2022-07-22T00:20:05-04:00",
"promoted_at":null,
"width":4160,
"height":6240,
"color":"#c0c0c0",
"blur_hash":"LPIOLgtR%1IT~qsSMxxZx]V#s.RP",
"description":null,
"alt_description":null,
"urls":{
"raw":"https://images.unsplash.com/photo-1657299156528-2d50a9a6a444?ixid=MnwzNDg3MDF8MXwxfGFsbHwxfHx8fHx8Mnx8MTY1ODQ4ODUyOQ\u0026ixlib=rb-1.2.1",
"full":"https://images.unsplash.com/photo-1657299156528-2d50a9a6a444?crop=entropy\u0026cs=tinysrgb\u0026fm=jpg\u0026ixid=MnwzNDg3MDF8MXwxfGFsbHwxfHx8fHx8Mnx8MTY1ODQ4ODUyOQ\u0026ixlib=rb-1.2.1\u0026q=80",
"regular":"https://images.unsplash.com/photo-1657299156528-2d50a9a6a444?crop=entropy\u0026cs=tinysrgb\u0026fit=max\u0026fm=jpg\u0026ixid=MnwzNDg3MDF8MXwxfGFsbHwxfHx8fHx8Mnx8MTY1ODQ4ODUyOQ\u0026ixlib=rb-1.2.1\u0026q=80\u0026w=1080",
"small":"https://images.unsplash.com/photo-1657299156528-2d50a9a6a444?crop=entropy\u0026cs=tinysrgb\u0026fit=max\u0026fm=jpg\u0026ixid=MnwzNDg3MDF8MXwxfGFsbHwxfHx8fHx8Mnx8MTY1ODQ4ODUyOQ\u0026ixlib=rb-1.2.1\u0026q=80\u0026w=400",
"thumb":"https://images.unsplash.com/photo-1657299156528-2d50a9a6a444?crop=entropy\u0026cs=tinysrgb\u0026fit=max\u0026fm=jpg\u0026ixid=MnwzNDg3MDF8MXwxfGFsbHwxfHx8fHx8Mnx8MTY1ODQ4ODUyOQ\u0026ixlib=rb-1.2.1\u0026q=80\u0026w=200",
"small_s3":"https://s3.us-west-2.amazonaws.com/images.unsplash.com/small/photo-1657299156528-2d50a9a6a444"
},
"links":{
"self":"https://api.unsplash.com/photos/RBo6ayiFND0",
"html":"https://unsplash.com/photos/RBo6ayiFND0",
"download":"https://unsplash.com/photos/RBo6ayiFND0/download?ixid=MnwzNDg3MDF8MXwxfGFsbHwxfHx8fHx8Mnx8MTY1ODQ4ODUyOQ",
"download_location":"https://api.unsplash.com/photos/RBo6ayiFND0/download?ixid=MnwzNDg3MDF8MXwxfGFsbHwxfHx8fHx8Mnx8MTY1ODQ4ODUyOQ"
},
"categories":[
],
"likes":21,
"liked_by_user":false,
"current_user_collections":[
],
"sponsorship":{
"impression_urls":[
"https://secure.insightexpressai.com/adServer/adServerESI.aspx?script=false\u0026bannerID=10624831\u0026rnd=[timestamp]\u0026redir=https://secure.insightexpressai.com/adserver/1pixel.gif"
],
"tagline":"Wholesome crispbread from Sweden",
"tagline_url":"https://www.wasa.com/global/",
"sponsor":{
"id":"5tdWPtk6hBg",
"updated_at":"2022-07-22T06:53:49-04:00",
"username":"wasacrispbread",
"name":"Wasa Crispbread",
"first_name":"Wasa Crispbread",
"last_name":null,
"twitter_username":null,
"portfolio_url":"https://www.wasa.com/global/",
"bio":"Things we love:\r\n🍞 Crispbread (naturally) 🌍 Our planet πŸ˜‹ Delicious food, everyday",
"location":null,
"links":{
"self":"https://api.unsplash.com/users/wasacrispbread",
"html":"https://unsplash.com/#wasacrispbread",
"photos":"https://api.unsplash.com/users/wasacrispbread/photos",
"likes":"https://api.unsplash.com/users/wasacrispbread/likes",
"portfolio":"https://api.unsplash.com/users/wasacrispbread/portfolio",
"following":"https://api.unsplash.com/users/wasacrispbread/following",
"followers":"https://api.unsplash.com/users/wasacrispbread/followers"
},
"profile_image":{
"small":"https://images.unsplash.com/profile-1655151625963-f0eec015f2a4image?ixlib=rb-1.2.1\u0026crop=faces\u0026fit=crop\u0026w=32\u0026h=32",
"medium":"https://images.unsplash.com/profile-1655151625963-f0eec015f2a4image?ixlib=rb-1.2.1\u0026crop=faces\u0026fit=crop\u0026w=64\u0026h=64",
"large":"https://images.unsplash.com/profile-1655151625963-f0eec015f2a4image?ixlib=rb-1.2.1\u0026crop=faces\u0026fit=crop\u0026w=128\u0026h=128"
},
"instagram_username":"wasacrispbread",
"total_collections":0,
"total_likes":0,
"total_photos":73,
"accepted_tos":true,
"for_hire":false,
"social":{
"instagram_username":"wasacrispbread",
"portfolio_url":"https://www.wasa.com/global/",
"twitter_username":null,
"paypal_email":null
}
}
},
"topic_submissions":{
},
"user":{
"id":"5tdWPtk6hBg",
"updated_at":"2022-07-22T06:53:49-04:00",
"username":"wasacrispbread",
"name":"Wasa Crispbread",
"first_name":"Wasa Crispbread",
"last_name":null,
"twitter_username":null,
"portfolio_url":"https://www.wasa.com/global/",
"bio":"Things we love:\r\n🍞 Crispbread (naturally) 🌍 Our planet πŸ˜‹ Delicious food, everyday",
"location":null,
"links":{
"self":"https://api.unsplash.com/users/wasacrispbread",
"html":"https://unsplash.com/#wasacrispbread",
"photos":"https://api.unsplash.com/users/wasacrispbread/photos",
"likes":"https://api.unsplash.com/users/wasacrispbread/likes",
"portfolio":"https://api.unsplash.com/users/wasacrispbread/portfolio",
"following":"https://api.unsplash.com/users/wasacrispbread/following",
"followers":"https://api.unsplash.com/users/wasacrispbread/followers"
},
"profile_image":{
"small":"https://images.unsplash.com/profile-1655151625963-f0eec015f2a4image?ixlib=rb-1.2.1\u0026crop=faces\u0026fit=crop\u0026w=32\u0026h=32",
"medium":"https://images.unsplash.com/profile-1655151625963-f0eec015f2a4image?ixlib=rb-1.2.1\u0026crop=faces\u0026fit=crop\u0026w=64\u0026h=64",
"large":"https://images.unsplash.com/profile-1655151625963-f0eec015f2a4image?ixlib=rb-1.2.1\u0026crop=faces\u0026fit=crop\u0026w=128\u0026h=128"
},
"instagram_username":"wasacrispbread",
"total_collections":0,
"total_likes":0,
"total_photos":73,
"accepted_tos":true,
"for_hire":false,
"social":{
"instagram_username":"wasacrispbread",
"portfolio_url":"https://www.wasa.com/global/",
"twitter_username":null,
"paypal_email":null
}
}
},
Picture Model:
class PictureModel {
const PictureModel({});
factory PictureModel.fromJson(Map < String, dynamic > json) {
return PictureModel(
...
);
}
}
If I understand correctly you only need:
image
title (I'll assume this is description)
author (I'll assume this is user.name)
You can create the PictureModel as follows:
class PictureModel {
final String author;
final String? title;
final String imageUrl;
const PictureModel({
required this.author,
this.title,
required this.imageUrl,
});
factory PictureModel.fromJson(Map<String, dynamic> json) {
return PictureModel(
author: json['user']['name'],
title: json['description'],
imageUrl: json['urls']['regular'],
);
}
}
Guessing you meant something like below by saying nested.
To simplify it, let's use Photo and Urls properties
class Photo {
Photo({
this.id,
this.urls,
...
});
String? id;
Urls? urls;
...
factory Photo.fromJson(Map<String, dynamic> json) {
return Photo(
id: json['id'],
urls: Urls.fromJson(json['urls']),
...
);
}
}
Then Urls object.
class Urls {
Urls({
this.rawUrl,
this.fullUrl,
this.regularUrl,
this.smallUrl,
this.thumbUrl,
this.smallS3Url,
});
String? rawUrl;
String? fullUrl;
String? regularUrl;
String? smallUrl;
String? thumbUrl;
String? smallS3Url;
factory Urls.fromJson(Map<String, dynamic> json) => Urls(
rawUrl: json['raw'],
fullUrl: json['full'],
regularUrl: json['regular'],
smallUrl: json['small'],
thumbUrl: json['thumb'],
smallS3Url: json['small_s3'],
);
Map<String, dynamic> toJson() => {
'rawUrl': rawUrl,
'fullUrl': fullUrl,
'regularUrl': regularUrl,
'smallUrl': smallUrl,
'thumbUrl': thumbUrl,
'smallS3Url': smallS3Url,
};
}
Simply you can use any JSON to Dart tool, that takes the JSON and returns a dart model like this one.
Or you can do it manually by making nested classes.
firstly you will make a parent class that contains the first level of the JSON file and each element containing other elements inside will be a separate class and you will use it as a type of the element.
so if we took the first level of the file and one other element from the second level such as the element user your code will be something like this:
class Pic {
Pic.fromJson(dynamic json) {
id = json['id'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
promotedAt = json['promoted_at'];
width = json['width'];
height = json['height'];
color = json['color'];
blurHash = json['blur_hash'];
description = json['description'];
altDescription = json['alt_description'];
urls = Urls.fromJson(json['urls']);
links = Links.fromJson(json['links']);
if (json['categories'] != null) {
categories = [];
json['categories'].forEach((v) {
categories?.add(Categories.fromJson(v));
});
}
likes = json['likes'];
likedByUser = json['liked_by_user'];
if (json['current_user_collections'] != null) {
currentUserCollections = [];
json['current_user_collections'].forEach((v) {
currentUserCollections?.add(CurrentUserCollections.fromJson(v));
});
}
sponsorship = json['sponsorship'] != null ? Sponsorship.fromJson(json['sponsorship']) : null;
topicSubmissions = json['topic_submissions'];
user = User.fromJson(json['user']);
}
String? id;
String? createdAt;
String? updatedAt;
dynamic promotedAt;
int? width;
int? height;
String? color;
String? blurHash;
dynamic description;
dynamic altDescription;
Urls? urls;
Links? links;
List<dynamic>? categories;
int? likes;
bool? likedByUser;
List<dynamic>? currentUserCollections;
Sponsorship? sponsorship;
dynamic topicSubmissions;
User? user;
}
class User {
User.fromJson(dynamic json) {
id = json['id'];
updatedAt = json['updated_at'];
username = json['username'];
name = json['name'];
firstName = json['first_name'];
lastName = json['last_name'];
twitterUsername = json['twitter_username'];
portfolioUrl = json['portfolio_url'];
bio = json['bio'];
location = json['location'];
links = json['links'] != null ? Links.fromJson(json['links']) : null;
profileImage = json['profile_image'] != null ? ProfileImage.fromJson(json['profile_image']) : null;
instagramUsername = json['instagram_username'];
totalCollections = json['total_collections'];
totalLikes = json['total_likes'];
totalPhotos = json['total_photos'];
acceptedTos = json['accepted_tos'];
forHire = json['for_hire'];
social = json['social'] != null ? Social.fromJson(json['social']) : null;
}
String? id;
String? updatedAt;
String? username;
String? name;
String? firstName;
dynamic lastName;
dynamic twitterUsername;
String? portfolioUrl;
String? bio;
dynamic location;
Links? links;
ProfileImage? profileImage;
String? instagramUsername;
int? totalCollections;
int? totalLikes;
int? totalPhotos;
bool? acceptedTos;
bool? forHire;
Social? social;
}
notice that each element that contains other elements inside is with a special data type like Urls Links Sponsorship User in the first class, and Links ProfileImage Social in the second class. so each of these data types is a class on its own but I only mentioned the class User to let you continue the rest of the code.
Happy Coding ;)

How to update Model with the correct value type

I have this code that fetch data from internet:
Future fetchCfo(String barCode, String url) async {
final response = await http.get(Uri.parse(url + barCode));
if (response.statusCode == 200) {
Map<String, dynamic> responseBody = json.decode(utf8.decode(response.bodyBytes));
responseBody.forEach((key, value) {
if (value == null) {
responseBody.update(key, (value) => "");
}
});
return CfoModel.fromJson(responseBody);
} else {
return null;
}
}
And I need to replace the null values ​​according to their type, for example if a field that was supposed to be an integer returns a null I need to replace it with 0, if a field that was supposed to be a list returns a null I need to replace it with a list empty []; and I don't know how to do this, my code replaces Strings but if a null appears in an int field, the code breaks.
For example, my model:
String? interfaceStatus;
bool? trasnP;
int? id;
String? name;
String? date;
bool? requiredStatus;
int? numberOf;
int? numberRegion;
List? parameters;
In case numberRegion returns a null, I need to replace with 0;
In case Transp returns a null, I need to replace with false;
in case name returns a null, I need to replace with empty String "";
Response I'm getting:
{
"interfaceStatus":"ok",
"trasnP":false,
"id":null,
"name":null,
"date":null,
"requiredStatus":true,
"numberOf":23,
"numberRegion":27,
"parameters":null
}
What I want to return:
{
"interfaceStatus":"ok",
"trasnP":false,
"id":0,
"name":"",
"date":"",
"requiredStatus":true,
"numberOf":23,
"numberRegion":27,
"Parameters":[
]
}
Anyone has a solution for this ?
I would recommend not updating any values in the responseBody just leave them as null but in the fromJson function you can give default values with the ?? operator such as:
fromJson(Map response) {
return CfoModel(
id: response[id] ?? 0,
array: response[array_element] ?? [],
);
}

Need help to get specific <key,Value> pair depeding upon a sinlge value from values in a Map

I am trying to get <key,Value> pairs thorugh a single value from values of map.
I am trying to display all the books that have status = true.
But i don't know how can i access status from librarian class(as status is member variable of Book class) and how i can get to the column of status as there are many value for each key.
BOOK CLASS
class Book {
String BookID = '';
String Author ='';
String Name='';
int RackNo=0;
int Price = 0;
bool status = true;
int Edition = 0;
String DateOfPurchase='';
static var count=0;
static var BookList = <String,Object>{};
Book(String BookID , String Author,String Name, int RackNo,int Price, bool status,int Edition,String DateOfPurchase){
this.BookID=BookID;
this.Author=Author;
this.Name=Name;
this.RackNo=RackNo;
this.Price=Price;
this.status=status;
this.Edition=Edition;
this.DateOfPurchase=DateOfPurchase;
BookList[this.BookID]={this.Name, this.Author,this.Name,this.RackNo,this.Price,this.status,this.Edition,this.DateOfPurchase};
count++;
}
void DisplayBookDetails(String ID){
print(BookList[ID]);
}
void UpDateStatus(bool newStatus){
status=newStatus;
}
}
Librarian Class
import 'package:untitled2/Book.dart';
class Librarian {
int count=0;
String Name = '';
String Password = '';
Librarian(String Name,String Password){
this.Name = Name;
this.Password=Password;
}
void SearchBook(String ID){
print(Book.BookList[ID]);
}
void ShowAvailableBooks() {
Book.BookList.values.forEach((element) {print(element);});
}
}
what i am trying to achieve is something like this
if(Book.BookList.values.status==true)//all the books tha have status == true
{
print(Book.BookList[ID's of those books])//display all those books
}
Sorry in advance for poor Question Composition as it is my first time asking a question
Here is an example. I changed your classes around because they were constructed weirdly and you had bookList as a static variable within Book, which wouldn't really work. The main functionality you asked for is in the showAvailableBooks function.
class Book {
final String id;
final String title;
final String? author;
final int? rackNo;
final int? price;
final int? edition;
final String? dateOfPurchase;
bool status;
Book({
required this.id,
required this.title,
this.author,
this.rackNo,
this.price,
this.edition,
this.dateOfPurchase,
this.status = false,
});
void set setStatus(bool newStatus) {
status = newStatus;
}
void printBook() {
print('id: $id, title: $title, author: $author');
}
}
class Librarian {
final String name;
final String password;
Map<String, Book> books = {};
int count = 0;
Librarian({required this.name, required this.password});
void addBooks(List<Book> bookList) {
for (Book book in bookList) {
books[book.id] = book;
count += 1;
}
}
void displayBookDetails(String id) {
books[id]?.printBook();
}
//The function you want
void showAvailableBooks() {
List<String> available = books.keys.where((id) => books[id]!.status == true).toList();
for (String bookID in available) {
books[bookID]?.printBook();
}
}
}
void main() {
Librarian librarian = Librarian(
name: "Mrs. Librarian",
password: "Password123",
);
//Unavailable - status: false
Book book1 = Book(
id: 'abc-123',
title: 'Book 1',
author: 'Author One',
);
//Available - status: true
Book book2 = Book(
id: 'def-456',
title: 'Book 2',
author: 'Author Two',
status: true
);
//Available - status: true
Book book3 = Book(
id: 'ghi-789',
title: 'Book 3',
author: 'Author Three',
status: true
);
librarian.addBooks([book1, book2, book3]);
/*The function you want - prints only books with status: true*/
print('Before changing book1 status to true');
librarian.showAvailableBooks();
book1.setStatus = true;
print('\nAfter changing book1 status to true');
librarian.showAvailableBooks();
}

How to compare the type variable in "is" operator in Dart

I couldn't find a way to store the Type value in Map so that I could use it in is operator to check the validity of type using this map later on. Also, can is operator accept Type as a variable?
For eg, Below is hypothetical code solving the problem but it's invalid.
Map<String, Type> map = {
"sku": String,
"price": double,
"quantity": int,
};
dynamic value = 10;
if(value is map["quantity"]){
print("value is of type int and int is expected for quantity value");
}
You can do something like this:
class TypeCheck<T> {
const TypeCheck();
bool typeCheck(dynamic value) => value is T;
}
void main() {
Map<String, TypeCheck> map = {
"sku": TypeCheck<String>(),
"price": TypeCheck<double>(),
"quantity": TypeCheck<int>(),
};
dynamic value = 10;
if (map["quantity"]!.typeCheck(value)) {
print("value is of type int and int is expected for quantity value");
}
}
Im not sure I fully understand I understand what you are trying to do but why don't you try something like.
bool _validate(Map productDetails){
if (productDetails.containsKey("sold_individually") && productDetails["sold_individually"] is bool) {
//return true or false
}
else if (productDetails.containsKey("stock_quantity") && productDetails["stock_quantity"] is int){
//return true or false
}
else if (productDetails.containsKey("tax_class") && productDetails["tax_class"] is String && productDetails["tax_class"].isNotEmpty) {
//return true or false
} else {
//return true or false
}
}
As for the other part of your question you wont get an error but you will always return false. In contrast if you check if a variable is dynamic it will always return true.
I don't really understand your end goal. But from what you have, I don't think you are taking advantage of the strongly-typed nature of dart.
Assuming you are getting your map from an API, you could enforce
typing manually in your code as follows;
Map<String, Type> map = {
"sku": json['key'] as String,
"price": json['key'] as double,
"quantity": json['key'] as int,
};
And avoid using dynamic when declaring variables.
OR
In the case you have a user-defined type you what to compare, you can use the equatable package on a class for instance as follows;
class CustomMap extends Equatable {
String sky;
double price;
int quantity;
// here you put the fields of a class you want for two instances of a class to be equal.
#overide
List<Object> get props => [sky, price, quantity];
}
Update from your comment
You should have a custom class for the API objects for instance;
class Item extends Equatable {
String sku;
double price;
int quantity;
Item({this.sky, this.price, this.quantity});
// factory constructor
factory Item.fromMap(Map<String, dynmic> json) {
final sku = json['sku'] as String,
final price = (json['price'] as num) as double,
final quantity = json['quantity'] as num,
return Item(sku: sku, price: price, quantity: quantity);
}
// define equatable objects
#override
List<Object> get props => [sku, price, quantity];
}
Now you can use it as follows;
Future<Item> objectsFromService(Map<String, dynamic> json ) async {
http.Response response = http.get(url);
if(response.status == 200) {
final decodedJson = json.decode(response.body);
return Item.fromJson(decodedJson);
}else{
print('Error fetch data');
return null;
}
}
Hope it helps