I'm watching the old flutter course because I couldn't really find a new one. But since flutter is constantly updated, it becomes a little more challenging as soon as you learn from the old courses.
Here is my questions:
Is fromObject still here or just changed to fromJson?
Do you have a model sample?
How can I do my _id is unique?(Usin sql etc.)
I'm trying something like this but I'm getting an error in 'Product.fromObject'.
class Product {
int _id;
String _name;
String _description;
double _price;
Product(this._id, this._name, this._description, this._price);
Product.withId(this._id, this._name, this._description, this._price);
int get id => _id;
String get name => _name;
String get description => _description;
double get price => _price;
set name(String value) {
if (value.length >= 2) {
_name = value;
}
}
set description(String value) {
if (value.length >= 10) {
_description = value;
}
}
set price(double value) {
if (value > 0) {
_price = value;
}
}
Map<String, dynamic> toMap() {
var map = <String, dynamic>{};
map["name"] = _name;
map["description"] = _description;
map["price"] = _price;
map["id"] = _id;
return map;
}
Product.fromObject(dynamic o) {
_id = o["id"];
_name = o["name"];
_description = o["description"];
_price = o["price"];
}
}```
Now It's changed to fromJson.
class Post{
int userid;
int id;
String title;
String body;
Post({userid, id, title, body});
Post fromJson(Map<String, dynamic> json){
Post post = Post();
post.userid = json["userId"];
post.id = json['id'];
post.title = json['title'];
post.body = json['body'];
return post;
}
Map<String, dynamic> toJson(Post post){
Map<String, dynamic> data = {
"userId": post.userid,
"id": post.id,
"title": post.title,
"body": post.body
};
return data;
}
}
I have attached a sample model class for your reference.
You can read about json serialization here: https://flutter.dev/docs/development/data-and-backend/json
The correct method to parse from json is a factory method that is called fromJson and takes a map.
Related
Hello guys this program consists of two pages named student list and studentdetail it don't make any error in the analyzer but in emulator when I open the first page that display list of students and tap on any student and go to the student detail and wanting to delete , update or goback to the fist page it says MissingpluginException(No implementation found for method getApplicationDocementsDirectory on channel plugins.flutter.io/path_provider in console and I can't delete or add student and in student page
class Student {
late int _id ;
late String _name;
late String _description;
late int _pass;
late String _date;
Student(this._name, this._description, this._pass, this._date);
Student.withId(
this._id, this._name, this._description, this._pass, this._date);
String get date => _date;
int get pass => _pass;
String get description => _description;
String get name => _name;
int get id => _id;
set date(String value) {
_date = value;
}
set pass(int value) {
if (value >= 1 && value <= 2) {
_pass = value;
}
}
set description(String value) {
if (value.length <= 255) {
_description = value;
}
}
set name(String value) {
if (value.length <= 255) {
_name = value;
}
}
Map<String, dynamic> toMap() {
var map = Map<String, dynamic>();
map["id"] = this._id;
map["name"] = this._name;
map["description"] = this._description;
map["pass"] = this._pass;
map["date"] = this._date;
return map;
}
Student.getMap(Map<String, dynamic> map) {
this._id = map["id"];
this._name = map["name"];
this._description = map["description"];
this._pass = map["pass"];
this._date = map["date"];
}
}
when i write late int _id ; it says late initialization error after field _id hasn't been initialized after add or delete student
this is the entire code
https://github.com/abdelrahman992-cpu/studentfinal
run these commands in terminals hope this will help you
>> flutter clean
>> flutter pub get
if this didn't worked try stopping and restarting the app. let me know if this help you or not.
I am new to flutter, I have Error in my model class Method Contact.fromSnapshot in which i want to convert snapsot to object. Error is on the brackets of snapshot.value[];. This is error:
The operator '[]' isn't defined for the type 'Object'. Try defining the operator '[]'.
How i can fix this error?
import 'package:firebase_database/firebase_database.dart';
class Contact {
String? _id;
String? _firstName;
String? _lastName;
String? _phone;
String? _email;
String? _address;
String? _photoUrl;
//Constructor for add
Contact(this._firstName, this._lastName, this._phone, this._email,
this._address, this._photoUrl);
//Constructor for Edit
Contact.withId(this._id, this._firstName, this._lastName, this._phone,
this._email, this._address, this._photoUrl);
//Getters
String? get id => _id;
String? get lastName => _lastName;
String? get firstName => _firstName;
String? get phone => _phone;
String? get email => _email;
String? get address => _address;
String? get photoUrl => _photoUrl;
//setters
set firstName(String? firstname) {
this._firstName = firstName;
}
set lastName(String? lastname) {
this._lastName = lastName;
}
set phone(String? phone) {
this._phone = phone;
}
set email(String? email) {
this._email = email;
}
set address(String? adress) {
this._address = address;
}
set photoUrl(String? photoUrl) {
this._photoUrl = photoUrl;
}
Contact.fromSnapshot(DataSnapshot snapshot) {
_id = snapshot.key;
_firstName = snapshot.value!['firstName'];
_lastName = snapshot.value!['lastName'];
_phone = snapshot.value!['phone'];
_email = snapshot.value!['email'];
_address = snapshot.value!['address'];
_photoUrl = snapshot.value!['photoUrl'];
}
}
It doesn't know snapshot.value is a map, so you need to tell it. You could try this:
Contact.fromSnapshot(DataSnapshot snapshot) {
Map<dynamic, dynamic> map = snapshot.value! as Map<dynamic, dynamic>;
_id = snapshot.key;
_firstName = map['firstName'];
_lastName = map['lastName'];
_phone = map['phone'];
_email = map['email'];
_address = map['address'];
_photoUrl = map['photoUrl'];
}
{"data":[{"id":"32f","regionName":"Korea","companyName":"Machine","catDealerCode":null},{"id":"cbb","regionName":"Korea","companyName":"KR","catDealerCode":null},{"id":"b6125b0e-5ec9",,"regionName":"China","companyName":"CHN","catDealerCode":null}],"code":0,"message":null}
I have data like the one you see above. I extract data according to the companyName. but some countries don't have data. I want to create an if else case within this.but no matter what I do when I say element == null it doesn't accept. Does anyone know where I am doing wrong? How should I create an if else for empty data?
onTap: () async {
List<Country> country =
await fetchList(
snapshot.data.code);
country.forEach((element) {
if(element.companyName == null){
print('element is empty');
}else{
print('Here ${element.companyName}');
}
});
},
And here's my country list data;
{"data":[{{"code":"KR","name":"Korea","isActive":true,"id":"71"},{"code":"RU","name":"Rusia","isActive":true,"id":"3c"},{"code":"Ch","name":"China","isActive":true,"id":"86"}],"code":0,"message":null}
class Country {
String id;
String companyCode;
String countryCode;
String countryId;
String regionName;
String companyName;
Null catDealerCode;
Country(
{this.id,
this.companyCode,
this.countryCode,
this.countryId,
this.regionName,
this.companyName,
this.catDealerCode});
Couuntry.fromJson(Map<String, dynamic> json) {
id = json['id'];
companyCode = json['companyCode'];
countryCode = json['countryCode'];
countryId = json['countryId'];
regionName = json['regionName'];
companyName = json['companyName'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['companyCode'] = this.companyCode;
data['countryCode'] = this.countryCode;
data['countryId'] = this.countryId;
data['regionName'] = this.regionName;
data['companyName'] = this.companyName;
return data;
}
}
I would go with null-aware operator:
onTap: () async {
List<Country> country =
await fetchList(
snapshot.data.code);
country?.forEach((element) {
if(element?.companyName == null){
print('element is empty');
}else{
print('Here ${element.companyName}');
}
});
},
My code works but I want to update this with objects. But I don't see how to add a property value to an object. It must be declared in the constructor ??
For exemple I have a user object with some property.
But in my code I need to classify users by those with the closest salary to a certain value.
For that I want to add an index key which I then use to organize them in order.
This key is just used to classify my users to have the order I want
This index key is not base defined in my object.
My class user :
class Users{
List<User> user;
Users({this.user});
Users.fromJson(Map<String, dynamic> json) {
if (json['user'] != null) {
user= new List<User>();
json['user'].forEach((v) {
user.add(new User.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.user!= null) {
data['user'] = this.user.map((v) => v.toJson()).toList();
}
return data;
}
#override
String toString() {
return '{${this.user}}';
}
}
class User{
String name;
int gender;
num salary;
User(
{this.name,
this.gender,
this.salary,
});
User.fromJson(Map<String, dynamic> json) {
name= json['name'];
gender= json['gender'];
salary= json['salary'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['gender'] = this.gender;
data['salary'] = this.salary;
return data;
}
#override
String toString() {
return '{ '
'${this.name},'
'${this.gender},'
'${this.salary},'
'}';
}
void add(String key, dynamic value) {
// ... implementation
}
}
Here an exemple of the function the classify my user and adding the index key in a functions.dart file
List<User> func_orderedItemByClosestSalary(List<User> filteredUsers)
{
switch (filteredUsers.length)
{
case 1:
// One result
print('un seul resultat ...');
filteredUsers[0].index = 0; // Not work for adding the index key
break;
The reason why filteredUsers[0].index = 0; doesn't work is because index isn't defined on Users object. Add index on Users to be able to update its value.
class User{
int index;
String name;
int gender;
num salary;
...
}
I've been wrapping my head around this issue for the past 2 hours (keep in mind that I'm new to Flutter). I'm trying to check if I've set up everything properly for getting a movie list from OMDB. Everything seems okay except the fact that I don't know how to access something inside a list ie. originalTitle.
This is the model:
class MovieItem {
int page;
int totalResults;
int totalPages;
List<Results> results;
MovieItem({this.page, this.totalResults, this.totalPages, this.results});
MovieItem.fromJson(Map<String, dynamic> json) {
page = json['page'];
totalResults = json['total_results'];
totalPages = json['total_pages'];
if (json['results'] != null) {
results = new List<Results>();
json['results'].forEach((v) {
results.add(new Results.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['page'] = this.page;
data['total_results'] = this.totalResults;
data['total_pages'] = this.totalPages;
if (this.results != null) {
data['results'] = this.results.map((v) => v.toJson()).toList();
}
return data;
}
}
class Results {
String posterPath;
int id;
String originalLanguage;
String originalTitle;
String title;
Results(
{this.posterPath,
this.id,
this.originalLanguage,
this.originalTitle,
this.title,});
Results.fromJson(Map<String, dynamic> json) {
posterPath = json['poster_path'];
id = json['id'];
originalLanguage = json['original_language'];
originalTitle = json['original_title'];
title = json['title'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['poster_path'] = this.posterPath;
data['id'] = this.id;
data['original_language'] = this.originalLanguage;
data['original_title'] = this.originalTitle;
data['title'] = this.title;
return data;
}
}
You are attempting to call a property on a List<Result> instead of Result. The property you are attempting to access exists on Result ... if there is a List of Result objects, what do you expect to return with movieItem.results.originalTitle? There could be any number of Result object with possibly different titles? If you just want to print them all out:
Future<MovieItem> movieItem() async {
var movieItem = await
client.movieItem();
movieItem.results.forEach((result) => print(result.originalTitle));
return movieItem;
}
The forEach will allow you to call the property and print it on every Result in the list
Your movieItem model class has list of result objects. So when you call the client.movieItem method the you get a MovieItem Object, and it you want to print the specific result item then just do this
print(movieItem.results[0].originalTitle)
and if you want to access all the objects from the result list then using for loop you can achieve it
for(int i=0;i<movieItem.results.length;i++)
{
print(movieItem.results[i].originalTitle);
}