The parameter isn't defined however, I defined it.
I saved my data onto firebase and also in the PostData object class however, when I try to fetch it, it tells me that the parameter isn't defined.
final FirebaseAuth _auth = FirebaseAuth.instance;
Future<void> fetchProducts() async {
PostData data;
final User user = _auth.currentUser;
final _uid = user.uid;
print('Fetch method is called');
await FirebaseFirestore.instance
.collection('post')
.get()
.then((QuerySnapshot productsSnapshot) {
_products = [];
productsSnapshot.docs.forEach((element) {
// print('element.get(productBrand), ${element.get('productBrand')}');
_products.insert(
0,
PostData(
0,
[],
Timestamp.now().millisecondsSinceEpoch,
name,
token,
image,
[],
title: element.get('productTitle'),
id: element.get('productId'),
description: element.get('productDescription'),
price: double.parse(
element.get('price'),
),
imageUrl: element.get('productImage'),
productCategoryName: element.get('productCategory'),
brand: element.get('productBrand'),
true,
// 0,
//
// [],
// Timestamp.now().millisecondsSinceEpoch,
//
// name,
// token,
// image,
// [],
// "",
// "",
// "",
// 0,
// "",
// "",
// "",
// true,
),);
});
});
}
Here is where I stored it, in PostData however, whenever I try to call it, it tells me that the parameter isn't defined. I am pretty sure I defined it so I don't know what to do or how to fix this issue.
PostData(
int likesCount,
List likes,
int timestamp,
String postersName,
String postersId,
String postersImageUrl,
List postSavedByUsers,
String title,
String id,
String description,
double price,
String imageUrl,
String productCategoryName,
String brand,
)
{
this.likesCount = likesCount;
this.likes = likes;
this.timestamp = timestamp;
this.postersName = postersName;
this.postersId = postersId;
this.postersImageUrl = postersImageUrl;
this.postSavedByUsers = postSavedByUsers;
this.title = title;
this.id = id;
this.description = description;
this.price = price;
this.imageUrl = imageUrl;
this.productCategoryName = productCategoryName;
this.brand = brand;
this.isPopular = isPopular;
}
here is the error i'm getting.
You're getting the error because you defined positional required parameters and not named parameters but you're trying to pass the name of the parameters (title, id, description, price, `imageUrl, productCategoryName, brand).
Solution:
Pass the arguments as positional required parameters (without the parameter names) like below:
PostData(
0,
[],
Timestamp.now().millisecondsSinceEpoch,
name,
token,
image,
[],
element.get('productTitle'),
element.get('productId'),
element.get('productDescription'),
double.parse(
element.get('price'),
),
element.get('productImage'),
element.get('productCategory'),
element.get('productBrand'),
)
Related
I've got a database that stores user information such as their name and all their friends. The DB look something like this:
{
"users": {
"userID here": {
"bio": "",
"country": "",
"dateOfBirth": "2022-04-13 17:49:45.906226",
"emergencyContacts": {
"mom": {
"emailAdd": "mom#gmail.com",
"name": "mom",
"phoneNumber": "07492017492",
"picUrl": "url here'"
}
},
"friends": {
"auto-generated ID (used push method)": {
"country": "",
"profilePicUrl": "url here",
"userID": "userID here",
"username": "newOne"
}
},
"fullName": "name",
"gender": "Female",
"hobbies": "[]",
"knownMH": "[]",
"lastMessageTime": "2022-04-14 08:44:40.639944",
}
}
I would like to access the "friends" node. While doing so, I'd also like to store the data in a 2d array. So, each sub-array will contain the data about the user we're currently looping through and one of their friends. This should happen until we've looped through all of the user's friends and then move on to the next user.
It's also worth mentioning; I've used a push method for adding friends so I get randomly assigned keys for the nodes.
I've used the method below, but it's not working, it's returning the wrong list of friends and not looping through all users. Please find the code that I've used below (any help is much appreciated):
void _retrieveAllFriendships() {
final allUsersDb = FirebaseDatabase.instance.ref().child('users');
_allUserssStream = allUsersDb.onValue.listen((event) {
if (event.snapshot.exists) {
final data = new Map<dynamic, dynamic>.from(
event.snapshot.value as Map<dynamic, dynamic>);
data.forEach((key, value) {
allUsersDb.child(key).onValue.listen((event) {
final acc = new Map<dynamic, dynamic>.from(
event.snapshot.value as Map<dynamic, dynamic>);
final username = acc['username'] as String;
final profilePicUrl = acc['profilePicUrl'] as String;
final country = acc['country'] as String;
final userID = acc['userID'] as String;
user = new FriendSuggestionModel(
picture: profilePicUrl,
name: username,
location: country,
userID: userID,
);
_friendshipStream = allUsersDb
.child(userID)
.child("friends")
.onValue
.listen((event) {
if (event.snapshot.exists) {
final data = new Map<dynamic, dynamic>.from(
event.snapshot.value as Map<dynamic, dynamic>);
data.forEach((key, value) {
allUsersDb
.child(userID)
.child("friends")
.child(key)
.onValue
.listen((event) {
final friend = new Map<dynamic, dynamic>.from(
event.snapshot.value as Map<dynamic, dynamic>);
final username = friend['username'] as String;
final profilePicUrl = friend['profilePicUrl'] as String;
final country = friend['country'] as String;
final userID = friend['userID'] as String;
friendModel = new FriendSuggestionModel(
picture: profilePicUrl,
name: username,
location: country,
userID: userID);
List<FriendSuggestionModel> friendship = [
user,
friendModel
];
allFriendships.add(friendship);
setState(() {
for (int i = 0; i < allFriendships.length; i++) {
print(
"${allFriendships[i][0].name} is friends with: ${allFriendships[i][1].name}");
}
});
});
});
}
});
});
});
}
});
}
When you attach a listener to allUsersDb.onValue all data under that path is already present in the event.snapshot and you don't need any more listeners for that data.
If you know the name of a child snapshot you want to access, you can get this by snapshot.child("friends"). If you don't know the name of the child snapshots, you can loop over all of them with snapshot.children.forEach.
I'm new to flutter and firebase (and yes i know this question has been asked before).
But i've seen plenty of different ways to map firebase data into provider, and some reason cannot get a single to work.
I have this data structure. And all i wish, is to Map it into an class / object.
Firebase screenshot
This is my data model.dart:
#immutable
class Requests {
Requests({
this.name = '',
this.pairingId = 0,
});
final String name;
final double pairingId;
Requests.fromJson(Map<String, Object?> json)
: this(
name: json['name']! as String,
pairingId: json['pairingId'] as double,
);
Map<String, Object?> toJson() {
return {
'name': name,
'pairingId': pairingId,
};
}
}
#immutable
class UserDataTest with ChangeNotifier {
UserDataTest({
this.firstName = '',
this.lastName = '',
this.gender = '',
this.dateOfBirth,
this.userUID = '',
this.uidp = '',
this.pairingId = 0,
this.requests = const [],
});
UserDataTest.fromJson(Map<String, Object?> json)
: this(
firstName: json['firstName']! as String,
lastName: json['lastName']! as String,
gender: json['gender']! as dynamic,
dateOfBirth: json['dateOfBirth']! as DateTime?,
userUID: json['userUID']! as String,
uidp: json['uidp']! as String,
pairingId: json['pairingId']! as double,
requests: json['requests']! as List<Requests>,
);
late final String firstName;
final String lastName;
final dynamic gender;
final DateTime? dateOfBirth;
final String userUID;
final String uidp;
final double pairingId;
final List<Requests> requests;
Map<String, Object?> toJson() {
return {
'firstName': firstName,
'lastName': lastName,
'gender': gender,
'dateOfBirth': dateOfBirth,
'userUID': userUID,
'uidp': uidp,
'pairingId': pairingId,
'requests': requests,
};
}
}
But from here i dont have any solution that works just partly.
Again, my wish is to be able to just write, ex. user.firstName and display the first Name. How do i get to there?
I know im missing the call to firebase, but i haven't been successful in making one.
I dont know if have to do something inside the provider.
(Yes i have a multiprovider at the top of my tree
and a call to the provider where im using it or wanting to)
My suggestion: start over. Just start by creating a simple class manually with just a few of the fields from Firebase, and work your way out. For example use the UserDataTest and just make it a class:
class UserDataTest {
String? firstName;
String? lastName;
UserDataTest({ this.firstName, this.lastName });
factory UserDataTest.fromJson(Map<String, dynamic> json) {
return UserDataTest(
firstName: json['firstName'],
lastName: json['lastName'],
);
}
}
Try to keep these classes as plain as possible. Create other classes for your services and then make those extend ChangeNotifier, like to encapsulate your business logic and trigger notifications.
Then, from Firebase you will easily be able to do stuff like:
List<UserDataTest> userData = [];
FirebaseFirestore.instance.collection('userdata').get().then((QuerySnapshot snapshot) {
userData = snapshot.docs.map((doc) => UserDataTest.fromJson(doc.data())).toList();
});
My two cents.
I want to save a device bluetooth information like id and name and etc.
When I want to save them in Firestore, I face this error.
And I have no DeviceIdentifier in my code.
addBluetoothInfo(var id, var name, var type, var isDiscoveringServices,
var services) async {
Map<String, dynamic> map = Map();
map['id'] = id;
map['name'] = name;
map['type'] = type;
map['isDiscoveringServices'] = isDiscoveringServices;
map['services'] = services;
await bluetoothRef.add(map).then((value) => print(value)).whenComplete(
() {
print('done');
},
);
}
I am trying to include a dynamic filter using string from firestore. The UI will show tiles based on a selection on filter(s)
I have have query to fetch Firebase documents below
getFoods(FoodNotifier foodNotifier) async {
QuerySnapshot snapshot = await Firestore.instance
.collection('Foods')
.orderBy('create at', descending: true)
.getDocuments();
List<Food> _foodList = [];
Here below these are the string I have setup in firestore.
import 'package:cloud_firestore/cloud_firestore.dart';
class Food {
String id;
String name;
String category;
String newcategory;
String image;
List subIngredients = [];
Timestamp createdAt;
Timestamp updatedAt;
static var data;
Food();
Food.fromMap(Map<String, dynamic> data) {
id = data['id'];
name = data['name'];
category = data['category'];
newcategory = data['newcategory'];
image = data['image'];
subIngredients = data['subIngredients'];
createdAt = data['create at'];
updatedAt = data['updatedAt'];
}
Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
'category': category,
'newcategory': newcategory,
'image': image,
'subIngredients': subIngredients,
'create at': createdAt,
'updatedAt': updatedAt,
};
}
If I understand you correctly, you are trying to build a query out of multiple conditions. Every time you call where it returns a new Query object. So by calling that for each condition, you can build up the query.
var query = Firestore.instance
.collection('Foods')
.orderBy('create at', descending: true);
if (food.category != "") {
query = query.where("category", isEqualTo: food.category);
}
if (food.name != "") {
query = query.where("name", isEqualTo: food.name);
}
QuerySnapshot snapshot = await query.getDocuments();
...
I wanted to get my users data from cloud firestore. It worked first but now it is raising a error.
"PlatformException (PlatformException(error, Invalid document reference. Document references must have an even number of segments, but users has 1, null))"
String name = "", email = "", pnumber = "", imgUrl = "", bio = "", posted = "", applied = "", rating = "", saved = "";
String url;
final formKey = new GlobalKey<FormState>();
final databaseReference = Firestore.instance;
String uID;
#override
void initState() {
super.initState();
uID = widget.uID;
print("UID " + uID);
getUser();
}
void getUser() {
try {
databaseReference
.collection('users')
.document(uID)
.get()
.then((DocumentSnapshot ds){
if (ds.exists) {
name = ds.data['fullname'].toString();
print(name);
email = ds.data['email'].toString();
print(email);
pnumber = ds.data['pnumber'].toString();
print(pnumber);
imgUrl = ds.data['imgUrl'].toString();
print(imgUrl);
bio = ds.data['bio'].toString();
print(bio);
posted = ds.data['posted'].toString();
print(posted);
applied = ds.data['applied'].toString();
print(applied);
rating = ds.data['rating'].toString();
print(rating);
saved = ds.data['saved'].toString();
print(saved);
print(ds.data['fullname'].toString());
} else {
print("No such user");
}
});
} catch (e) {
print(e.toString());
}
}
This is almost certainly because uID is an empty string. Check it before passing to Firestore.