How to create more children on Firebase Realtime Database - flutter

I want to create more children on the Firebase Realtime Database.
Desired effect (example): [
What I have:
MyButton(
label: "Create Ride",
onTap: () {
ref
.child('Database')
.push()
.child('Title')
.set(_titleController.text)//the Title Controller is just the
//data you type in
.asStream();
_titleController.clear();
}),
I can't find a sample anywhere and I don't know how to write it so that there's more than just a title.

If you want to write multiple values under the new child, you can do:
ref
.child('Database')
.push()
.set({
'Title': _titleController.text,
'land': 'Germany',
'stadt': 'Berlin'
})
Also see the example in the Firebase documentation on writing data.

Related

Flutter how to update list in firebase document

I am trying to update a field on firebase from my flutter app but it doesn't work.
activities is an array, 0 a map.
I want to update 'daysdone' with 'val' from my flutter app.
ChipsChoice<String>.multiple(
value: activities
.elementAt(i)
.daylistdone,
onChanged: (val) =>
FirebaseFirestore.instance
.collection(
widget.user.user.uid)
.doc(documentName)
.set({
"activities." + i.toString(): {
'title': activities
.elementAt(i)
.title,
'days': activities
.elementAt(i)
.daylist,
'daysdone': val,
'daysbool': activities
.elementAt(i)
.daybool,
// 'daysdonebool': myData2bool2,
'notification': activities
.elementAt(i)
.notification,
'time':
activities.elementAt(i).time
},
}),
choiceItems: C2Choice.listFrom<
String, String>(
source: activities
.elementAt(i)
.daylist,
value: (i, v) => v,
label: (i, v) => v,
),
),
It gives me this result
What can I do to fix this issue?
The first image is a list of maps. The only way you can update the field daysdone is by accessing the entire list, and then traversing through the list to your desired map position (in the first image case, this should be position 0), then editing that particular map. After doing this, you have to update the entire activities field:
FirebaseFirestore.instance.collection('collection').doc('Mydocument').update({'activities': newEditedList})
I would personally recommend a complete re-structure of your database-collection. Like the following:
Step 1
Step 2: Each user has sub-collection: Activities
Step 3: Each activity can now easily be accessed
To access a user's activities:
var result
= await FirebaseFirestore.instance.collection('MyUsers').doc(widget.user.user.uid).collection('Activities').limit(20).get(GetOptions(source:Source.server));
If you want to update color field:
// Color
FirebaseFirestore.instance.collection('MyUsers').doc(widget.user.user.uid).update({'color':'red'});
If you want to update an activity :
//days done
FirebaseFirestore.instance.collection('MyUsers').doc(widget.user.user.uid).collection('Activities').doc('the_activityId').update({'daysdone': "value"});

Passing model object as an argument with Flutter GetX

I need a model object on two screens.
I have 2 questions:
Is passing a model object (from one screen to another) required if we are using GetX?
If yes, how do we do it?
return GestureDetector(
onTap: () {
Get.toNamed('/field_details/', arguments: fieldModel);
},
In main.dart:
GetPage(
name: '/field_details',
page: () => FieldDetailsScreen(//how do I get the model to be passed here, it won't be available in the main function),
),
You can use Get.arguments for that.
GetPage(
name: '/field_details',
page: () => FieldDetailsScreen(Get.arguments),
),
You will get your model here but you need to convert arguments into model by using your model's fromjosn method.

1 QuerySnapshot returning null in Flutter web app but gives result in the Android console

I am having an issue where the QuerySnashot from the firestore giving correct value when printing in the android console but returns a null when building it on the flutter web app. Can someone please assist on what I am doing wrong?
Here is the function giving me the correct print:
countpassengers() async {
String collection = "users";
QuerySnapshot _myDoc = await firebaseFiretore.collection(collection).get();
List<DocumentSnapshot> _myDocCount = _myDoc.docs;
print("Number of Users: :::::::::::::");
print(_myDocCount.length); // Count of Documen
totalusers = _myDocCount.length.toString() ;//ts in Collection
print (totalusers.toString());
return totalusers ;
}
and here is how I am calling it (returning null) somehow
InfoCard(
title: "Number of Passengers",
value: totalusers.toString(),//"3",
onTap: () {},
topColor: Colors.orange,
),
When you are returning the output from a function to State you need to rebuild the state by calling setState function.
By calling setState, the whole StatefulWidget knows something is updated and rebuild the state with new data. So insert setState after calling your Firestore function in the class. It could be inside a function or inside onTap: (){}.
If you call that function inside your onTap: (){}, don't forget to add async like that: onTap: () async{} and await your returning data.

Can Anyone Explain how to make a Searchable DropDown to select countries using api/json? in Flutter

I want to make a dropdown list, in which one can select the country. The drop down list must be searchable, whenever we type a letter, the drop down list changes.
The drop down list is using a api/json data.
We are not making selection Manually.
you can use searchable_dropdown or dropdown_search packages
For API/JSON question :
check out the second package example in Readme
example
DropdownSearch<UserModel>(
label: "Name",
onFind: (String filter) async {
var response = await Dio().get(
"http://5d85ccfb1e61af001471bf60.mockapi.io/user",
queryParameters: {"filter": filter},
);
var models = UserModel.fromJsonList(response.data);
return models;
},
onChanged: (UserModel data) {
print(data);
},
);

Best way to update a listview based on date from a firestore collection

I have a document in firestore having a name field and a date field.I also have a stream setup which fetches data from firestore like below
List<Object> _objectDetailsfromSnapshot(QuerySnapshot snapshot) {
return snapshot.documents.map((doc) {
return Object(
date: doc.data['date'] ?? Timestamp.now(),
name: doc.data['name'] ?? ''
);
}).toList();
}
Stream<List<Object>> get objList {
return collection.snapshots().map(_objectDetailsfromSnapshot);
}
And then am using the where condition to fetch the items for today. Using this am populating a listview.
The issue is when the current date changes from yesterday to today, my list view still shows the items of yesterday.
I want the listview to automatically show today's items. What way I can adopt to achieve this.Please help.
Since it's a stream, it should automatically change if you update the date or post something new. Check the date format properly. For saving the date in Firestore use,
'date' : FieldValue.serverTimestamp(),
And the stream will be
Firestore.instance.collection('objects').orderBy('date', descending: true).snapshots(),
Then in your StreamBuilder
return Container(
ListView(
children: snapshot.data.documents.map((doc) =>
_objectList(doc)).toList(),
),
),
Widget _objectList(DocumentSnapshot doc){
return ListTile(
title: Text(documentSnapshot.data['name']),
subtitle: Text(documentSnapshot.data['name']),
);
}