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'];
}
Related
I am getting null value from api with variable of storeUserID, in this variable i stored user id at the time of register but when i run app it shows null value.
But when i manully type id like this https://aeliya.000webhostapp.com/demo.php?id=106764933065187174744 is shows me data.
//get users details
Future<GetUserData> getUserDetail() async {
var url = "https://aeliya.000webhostapp.com/demo.php?id=$storeUserID";
var response = await http.get(Uri.parse(url));
var data = jsonDecode(response.body.toString());
if (response.statusCode == 200) {
print(data);
print(storeUserID);
//print(data[0]['isAdmin']);
return GetUserData.fromJson(data);
} else {
return GetUserData.fromJson(data);
}
}
at the same time i am getting following error.
E/flutter (13406): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)]
Unhandled Exception: type 'String' is not a subtype of type 'int' of
'index' E/flutter (13406): #0 new GetUserData.fromJson
(package:mahuva_azadari/Models/GetUserData.dart:19:17) E/flutter
(13406): #1 _AdminReqState.getUserDetail
(package:mahuva_azadari/Screens/Admin%20Request.dart:352:26) E/flutter
(13406):
Following is my response:
[{"name":"Taki Rajani","email":"mohammadtaki.rajani#gmail.com","isAdmin":"0","description":"testing "}]
GetUserData
/// name : "Taki Rajani"
/// email : "mohammadtaki.rajani#gmail.com"
/// isAdmin : "0"
/// description : "testing "
class GetUserData {
GetUserData({
String? name,
String? email,
String? isAdmin,
String? description,}){
_name = name;
_email = email;
_isAdmin = isAdmin;
_description = description;
}
GetUserData.fromJson(dynamic json) {
_name = json['name'];
_email = json['email'];
_isAdmin = json['isAdmin'];
_description = json['description'];
}
String? _name;
String? _email;
String? _isAdmin;
String? _description;
GetUserData copyWith({ String? name,
String? email,
String? isAdmin,
String? description,
}) => GetUserData( name: name ?? _name,
email: email ?? _email,
isAdmin: isAdmin ?? _isAdmin,
description: description ?? _description,
);
String? get name => _name;
String? get email => _email;
String? get isAdmin => _isAdmin;
String? get description => _description;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['name'] = _name;
map['email'] = _email;
map['isAdmin'] = _isAdmin;
map['description'] = _description;
return map;
}
}
so I see the error in
Models/GetUserData.dart
I think in your model
"isAdmin":"0" you save it as int but it is returning from the api as String
Try this.
Future<GetUserData> getUserDetail() async {
var url = "https://aeliya.000webhostapp.com/demo.php?id=$storeUserID";
var response = await http.get(Uri.parse(url));
var data = jsonDecode(response.body.toString());
if (response.statusCode == 200) {
print(data);
print(storeUserID);
//print(data[0]['isAdmin']);
return GetUserData.fromJson(data[0]); <--- made this change
} else {
return GetUserData.fromJson(data);
}
}
I got an error when I fetch the array data from FireStore.
I added "blockUid" field on FireStore.
but It's not working, despite the others are all working.
github:https://github.com/ATUSHIKADOWAKI/dance_4_life/tree/main/lib
(main_model.dart)
Future<void> fetchEvents() async {
final docs = await FirebaseFirestore.instance
.collection('event')
.orderBy('timestamp', descending: true)
.get();
final events = docs.docs.map((doc) => Events(doc)).toList();
this.events = events;
notifyListeners();
}
(events.dart)
class Events {
String? eventId;
String? title;
String? date;
String? imgURL;
String? detail;
//array is here.
List<String?> blockUid = [];
String? eventPlace;
String? eventAddress;
String? eventCategory;
String? eventPrice;
String? eventGenre;
Events(DocumentSnapshot doc) {
eventId = doc.id;
title = doc['title'];
eventPlace = doc['eventPlace'];
eventAddress = doc['eventAddress'];
eventCategory = doc['eventCategory'];
eventPrice = doc['eventPrice'];
eventGenre = doc['eventGenre'];
date = doc['date'];
imgURL = doc['imgURL'];
detail = doc['detail'];
blockUid = doc['blockUid'];
}
}
You need to change this line
blockUid = doc['blockUid'];
to
blockUid = doc['blockUid'] as List<String>;
please replace
blockUid = doc['blockUid'];
with this
blockUid = List<String>.from(doc["data"].map((x) => x) ?? [])
Make sure all the data in the blockUid list in Firestore is String and try this:
Future<void> fetchEvents() async {
final docs = await FirebaseFirestore.instance
.collection('event')
.orderBy('timestamp', descending: true)
.get();
final events = docs.docs.map((doc) => Events.fromDoc(doc)).toList();
this.events = events;
notifyListeners();
}
class Events {
Events({
this.eventId,
this.title,
this.date,
this.imgURL,
this.detail,
this.blockUid,
this.eventPlace,
this.eventAddress,
this.eventCategory,
this.eventPrice,
this.eventGenre,
});
String? eventId;
String? title;
String? date;
String? imgURL;
String? detail;
//array is here.
List<String>? blockUid;
String? eventPlace;
String? eventAddress;
String? eventCategory;
String? eventPrice;
String? eventGenre;
factory Events.fromDoc(DocumentSnapshot doc) => Events(
eventId: doc.id,
title: doc['title'],
eventPlace: doc['eventPlace'],
eventAddress: doc['eventAddress'],
eventCategory: doc['eventCategory'],
eventPrice: doc['eventPrice'],
eventGenre: doc['eventGenre'],
date: doc['date'],
imgURL: doc['imgURL'],
detail: doc['detail'],
blockUid: doc['blockUid'],
);
}
You only need to do Replace this
List<dynamic> blockUid = [];
Cast individual item to String, something like this:
Events(DocumentSnapshot doc) {
eventId = doc.id;
title = doc['title'];
...
blockUid = doc['blockUid'].map((item) => item as String).toList()
}
In my app these is a localdb containing user data which i have parsed from API. My objective is to get these values from local table and use that values for state management using provider. I have created a model class for the table
class UserTable {
int? id;
String? accountDetails;
String? accountId;
String? childName;
String? childGender;
int? expiry;
int? finalSequenceNo;
int? packageIndex;
String? parentName;
String? productType;
String? userId;
int? age;
int? dob;
int? nextSyncTime;
String? productSubType;
String? validTill;
int? latestUpdatePkgSeqNo;
int? guidedTour;
UserTable(
{this.id,
this.accountDetails,
this.accountId,
this.childName,
this.childGender,
this.expiry,
this.finalSequenceNo,
this.packageIndex,
this.parentName,
this.productType,
this.userId,
this.age,
this.dob,
this.nextSyncTime,
this.productSubType,
this.validTill,
this.latestUpdatePkgSeqNo,
this.guidedTour,
});
Map<String, dynamic> toMap() {
var map = <String, dynamic>{
DatabaseHelper.USER_TABLE_ID: id,
DatabaseHelper.ACCOUNT_DETAILS: accountDetails,
DatabaseHelper.ACCOUNT_ID: accountId,
DatabaseHelper.USER_CHILD_NAME: childName,
DatabaseHelper.USER_CHILD_GENDER: childGender,
DatabaseHelper.EXPIRY: expiry,
DatabaseHelper.FINAL_SEQ_NO: finalSequenceNo,
DatabaseHelper.PACKAGE_INDEX: packageIndex,
DatabaseHelper.PARENT_NAME: parentName,
DatabaseHelper.PRODUCT_TYPE: productType,
DatabaseHelper.USER_ID: userId,
DatabaseHelper.AGE: age,
DatabaseHelper.DOB: dob,
DatabaseHelper.NEXT_SYNC_TIME: nextSyncTime,
DatabaseHelper.PRODUCT_SUB_TYPE: productSubType,
DatabaseHelper.VALID_TILL: validTill,
DatabaseHelper.LATEST_UPDATED_PKG_SEQ_NO: latestUpdatePkgSeqNo,
DatabaseHelper.GUIDED_TOUR: guidedTour,
};
if (id != null) {
map[DatabaseHelper.USER_TABLE_ID] = id;
}
return map;
}
UserTable.fromMap(Map<String, dynamic> map) {
id = map[DatabaseHelper.USER_TABLE_ID];
accountDetails = map[DatabaseHelper.ACCOUNT_DETAILS];
accountId = map[DatabaseHelper.ACCOUNT_ID];
childName = map[DatabaseHelper.USER_CHILD_NAME];
childGender = map[DatabaseHelper.USER_CHILD_GENDER];
expiry = map[DatabaseHelper.EXPIRY];
finalSequenceNo = map[DatabaseHelper.FINAL_SEQ_NO];
packageIndex = map[DatabaseHelper.PACKAGE_INDEX];
parentName = map[DatabaseHelper.PARENT_NAME];
productType = map[DatabaseHelper.PRODUCT_TYPE];
userId = map[DatabaseHelper.USER_ID];
age = map[DatabaseHelper.AGE];
dob = map[DatabaseHelper.DOB];
nextSyncTime = map[DatabaseHelper.NEXT_SYNC_TIME];
productSubType = map[DatabaseHelper.PRODUCT_SUB_TYPE];
validTill = map[DatabaseHelper.VALID_TILL];
latestUpdatePkgSeqNo = map[DatabaseHelper.LATEST_UPDATED_PKG_SEQ_NO];
guidedTour = map[DatabaseHelper.GUIDED_TOUR];
}
}
How can I retrieve data from localdb , so that I can use that data for statemanagement. Below is how now i'm retrieving data.
Future<List<UserTable>> getAllUserData() async {
final db = await this.database;
final List<Map<String, dynamic>> map =
await db!.rawQuery("SELECT * FROM $TABLE_USER");
List<UserTable> list = map.isNotEmpty?map.map((e) => UserTable.fromMap(e)).toList():[];
return list;
How can i achieve this? please suggest any workarounds
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.
I am having this error and i dont know how to resolved it pls help me out:
The method 'where' was called on null.
Receiver: null
Tried calling: where(Closure: (UserModel) => bool)
This is where the error is coming from:
The List is of type the UserModel class which is writen below
List<UserModel> userList;
final List<UserModel> suggestionList = query.isEmpty
?[]
: userList.where((UserModel user) {
String _getUsername = user.username.toLowerCase();
String _query = query.toLowerCase();
String _getName = user.name.toLowerCase();
bool matchesUsername = _getUsername.contains(_query);
bool matchesName = _getName.contains(_query);
return (matchesUsername || matchesName);
}).toList();
This is the class which the userList is calling from:
This is the Model class that is begin called.
class UserModel {
String uid;
String name;
String email;
String username;
String status;
int state;
String profilePhoto;
UserModel({
this.uid,
this.name,
this.email,
this.username,
this.status,
this.state,
this.profilePhoto,
});
Map toMap(UserModel user) {
var data = Map<String, dynamic>();
data['uid'] = user.uid;
data['name'] = user.name;
data['email'] = user.email;
data['username'] = user.username;
data["status"] = user.status;
data["state"] = user.state;
data["profile_photo"] = user.profilePhoto;
return data;
}
UserModel.fromMap(Map<String, dynamic> mapData) {
this.uid = mapData['uid'];
this.name = mapData['name'];
this.email = mapData['email'];
this.username = mapData['username'];
this.status = mapData['status'];
this.state = mapData['state'];
this.profilePhoto = mapData['profile_photo'];
}
}
The "userList" variable is not initialized. The easiest fix you can do is to initialize it with an empty list when you declare it.
List<UserModel> userList = <UserModel>[];