How to passing final List<File> keepImage = [] to next page - firebase

How to passing the list of image to next page i try to declare at the top of code and do like this but it said
PostView({File? keepImage}) : this.keepImage = keepImage ?? [];
'keepImage' isn't a field in the enclosing class.
Try correcting the name to match an existing field, or defining a field named
i have keep image into
final List<File> keepImage = [];
and here is pick image function
Future<void> chooseImage() async {
final pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
keepImage.add(File(pickedFile!.path));
});
if (pickedFile?.path == null) retrieveLostData();
}
Future<void> retrieveLostData() async {
final LostData response = await picker.getLostData();
if (response.isEmpty) {
return;
}
if (response.file != null) {
setState(() {
keepImage.add(File(response.file!.path));
});
} else {
print(response.file);
}
}

There are several ways you can do this.
The easiest is using shared preferences to store the image url in cache and so you can retrieve it wherever you want. Another is using arguments, when navigating to the other page, pass the id of this image for it.

Related

I want to convert realtime database to cloud firestore

Below is the code that I need to convert
DatabaseReference driversRef =
FirebaseDatabase.instance.reference().child("drivers");
driversRef
.child(currentfirebaseUser!.uid)
.once()
.then((DataSnapshot dataSnapShot) {
if (dataSnapShot.value != null) {
driversInformation = Drivers.fromSnapshot(dataSnapShot);
}
})
I have set up cloud store but I can't seem to get the code write to translate what I have to firestore.
This is my try
:
driversRef
.doc(currentfirebaseUser!.uid)
.collection('earnings')
.get()
.then((value) {
if (value != null) {
driversInformation = value.toString();
}
});
below is a picture of database structure
I think you are using collection('earning) after the Doc is wrong. because you can use it in starting & once just like table name.
you can try this
final databaseReference = FirebaseFirestore.instance;
databaseReference.collection('drivers').doc(currentfirebaseUser!.uid).snapshots().listen((event) {
//If you want to listen like streaming
evenyt.data(); //<- access data in <String,dynamic>
}
// If you want to list only once
var response = await databaseReference.collection('drivers').doc(currentfirebaseUser!.uid).get();
response.data()?['earning'] ?? 0 // access specific key value
here I show you my example similar to you:
I am updating notification badge values when it will change.
here is my cloud firestore structure.
//If you want to listen only once
Future<int> getBadgeCount({required String uid}) async {
var response = await databaseReference.collection('Badges').doc(uid).get();
return (response.data() != null) ? (response.data()?['BadgeCount'] ?? 0) : 0;
}
//If you want to listen like streaming
databaseReference.collection('Badges').where(uid).limit(1).snapshots().listen((response) {
badgeCount = response.docs.isNotEmpty ? (response.docs.first.data()['BadgeCount'] ?? 0) : 0;
printLog(message: "BadgeCount: ", variable: badgeCount);
});
}

How to add multiple images in flutter (firebase)

how I can add multiple images and store them in an array in firebase ?
every container has a + button so the user can add single image per container then I WANT TO STORE them in my firebase
any help would be greatly appreciated ^^
what you are showing in your image is fbCloudStore which is use to store information in json structure.
To store the images you may use fbStorge.
here's an snippet I use on my project:
Future<String?> uploadFile({
required FilePickerResult file,
required String fileName,
required FirebaseReferenceType referenceType,
}) async {
try {
final ref = _getReference(referenceType);
final extension = path.extension(file.files.first.name);
final _ref = ref.child(fileName + extension);
late UploadTask uploadTask;
if (kIsWeb) {
uploadTask = _ref.putData(file.files.first.bytes!);
} else {
uploadTask = _ref.putFile(File(file.files.single.path!));
}
var url;
await uploadTask.whenComplete(
() async => url = await uploadTask.snapshot.ref.getDownloadURL());
print(url);
return url;
} on FirebaseException catch (_) {
print(_);
}
}
Note that I'm returning the URL of fbStorage in order to associate it with fbCloudStorage
final url =
await FirebaseStorageSer.to.uploadFile(
file: result,
fileName: STORAGE_USER_PROFILE_PICTURE,
referenceType: FirebaseReferenceType.user,
);
if (url != null) {
await FirebaseAuthSer.to
.updateUserProfile(photoUrl: url);
}
FirebaseReferenceType.user is just a simple enum to simplify ref targets.

Flutter Firebase async query not retrieving data inside a stream function

I am trying to query a User from firebase within another query but for some reason but I can't get the code to work
The function the wont run is await usersRef.doc(uid).get(); and can be found here:
static getUserData(String uid) async {
return await usersRef.doc(uid).get();
}
static DirectMessageListModel getDocData(QueryDocumentSnapshot qdoc, String uid) {
Userdata postUser = Userdata.fromDoc(getUserData(uid));
return DirectMessageListModel.fromDoc(qdoc, postUser);
}
static DirectMessageListModel fromDoc(QueryDocumentSnapshot doc, Userdata altUser) {
return DirectMessageListModel(
doc['chatId'],
doc['lastMsgContent'],
doc['lastMsgType'],
altUser
);
}
parent function:
Stream<List<DirectMessageListModel>> getMeassageList(){
var snaps = FirebaseFirestore.instance.collection('directMessages').where('users', arrayContains: userdata!.uid).snapshots();
List<String> usersListElement = [];
return snaps.map((event) { return event.docs.map((e) {
usersListElement = [e.get('users')[0], e.get('users')[1]];
usersListElement.remove(userdata!.uid);
return DirectMessageListModel.getDocData(e, usersListElement.first);
}).toList();
});
}
You forgot to wait for the future getUserData(uid) to complete.
Try this:
static Future<DocumentSnapshot<Object>> getUserData(String uid) async {
return await usersRef.doc(uid).get();
}
static DirectMessageListModel getDocData(
QueryDocumentSnapshot qdoc,
String uid,
) async {
Userdata postUser = Userdata.fromDoc(await getUserData(uid)); // await here
return DirectMessageListModel.fromDoc(qdoc, postUser);
}
..
// parent function.
// Also wait for the future in the parent function.
// UPDATE BELOW! Define the parent function like this:
Stream<List<Future<DirectMessageListModel>>> getMeassageList() {
var snaps = FirebaseFirestore.instance
.collection('directMessages')
.where('users', arrayContains: userdata!.uid)
.snapshots();
List<String> usersListElement = [];
return snaps.map((event) {
return event.docs.map((e) async {
usersListElement = [e.get('users')[0], e.get('users')[1]];
usersListElement.remove(userdata!.uid);
return await DirectMessageListModel.getDocData(e, usersListElement.first);
}).toList();
});
}
NB: You are fetching user data (either sender/receiver) for each message in directMessages collection. It might be better to store just sender/receiver name in directMessages collection and simply display that. Then if the user clicks on a message, you can then fetch the full sender/receiver data.

How to check if string already exists in list?

Im trying to create a list of string which has array from firebase . And that works perfectly. But now I wanna filter the list a bit . So what I want is add allhastags one time . So if a hashtags exist twice I wanna just put it int he list once. Heres my code
Future<List<String>> getHashtags() async {
List<String> allVideoHastags = [];
QuerySnapshot snapshots =
await FirebaseFirestore.instance.collection('videos').get();
for (QueryDocumentSnapshot videoSnapshot in snapshots.docs) {
List<String> videoHastags =
List.from(videoSnapshot.data()['Hashtagsforallvideos']);
allVideoHastags.addAll(videoHastags);
}
_allResults = allVideoHastags;
searchResults();
return allVideoHastags;
}
So before adding the hashtags into the list ,I wanna check if it already exists in the list of strings .Hope anyone can help .If you need more information please leave a comment
Just loop over the hashtags you get from firebase and add them to your results only if they are not already in there like this:
Future<List<String>> getHashtags() async {
List<String> allVideoHastags = [];
QuerySnapshot snapshots =
await FirebaseFirestore.instance.collection('videos').get();
for (QueryDocumentSnapshot videoSnapshot in snapshots.docs) {
List<String> videoHastags =
List.from(videoSnapshot.data()['Hashtagsforallvideos']);
videoHastags.forEach((element) {
if(!allVideoHastags.contains(element)){
allVideoHastags.add(element);
}
});
}
_allResults = allVideoHastags;
searchResults();
return allVideoHastags;
}
This would remove all duplicates from a list
_allResults = allVideoHastags.toSet().toList();
YOUR_LIST.forEach((element) => if(element == "YOUR_STRING") {YOUR_NEW_LIST.add(element )});

How to retrieve value of child data from firebase DB?

I am trying to grab the children data from a certain movie title in a database, but I can only get an output of "Instance of Datasnapshot."
Here is the setup of the DB with the highlighted information I am trying to store in a list:
I tried using the following code with no success:
Future<List<String>> getMovieDetails(String movieName) async {
DataSnapshot movies = await DBRef.child("Movies").child(movieName).once().then((DataSnapshot datasnapshot)
{
print(datasnapshot.value.toString());
});
var moviesMap = Map<String, dynamic>.from(movies.value);
List<String> moviesList = [];
moviesMap.forEach((key, value){
moviesList.add(key);
print('My-Key $key');
print('Movie List: $moviesList');
});
return moviesList;
}
Note: I am passing the selected movie name so I only grab the child information from the movie the user selects. This portion is correctly, if the user clicks on the list tile of Batman, the title will be passed to this getMovieDetails() function.
Try the following:
Future<List<String>> getMovieDetails(String movieName) async {
DataSnapshot movies = await FirebaseDatabase.instance
.reference()
.child("Movies")
.child(movieName)
.once();
var moviesMap = Map<String, dynamic>.from(movies.value);
List<String> moviesList = [];
moviesMap.forEach((key, value) {
moviesList.add(value);
print('My-Key $key');
print('My-Value $value');
});
return moviesList;
}
}
You dont have to use then() since you are using await. Also when you call this method, you need to do for example:
await getMovieDetails("Batman");
I will make the above answer as correct, but the biggest issue was when I did:
moviesList.add(key)
When it should be:
moviesList.add(value)

Resources