'How to update data from Firestore in Flutter?
I want to use update method in FirebaseFirestore instance but it is not working. I have intialized id as String i.e String Id in the stateful widget
This is ViewData Page which has a button Widget
class ViewData extends StatefulWidget {
const ViewData({Key? key, required this.document, required this.id})
: super(key: key);
final Map<String, dynamic> document;
final String id;
Widget button() {
return InkWell(
onTap: () {
FirebaseFirestore.instance.collection("mytask").doc(widget.id).update({
"title": titleController.text,
"description": descriptionController.text,
"type": type,
"category": category,
"format": format,
});
Navigator.pop(context);
},
child: Container(
height: 56,
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
),
child: const Center(
child: Text(
"Update",
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.w600,
),
),
),
),
);
}
There is another page named Homepage where Snapshot has been written.
return ListView.builder(
itemCount: snapshot.data.docs.length,
itemBuilder: (context, index) {
Map<String, dynamic> document = snapshot.data.docs[index]
.data() as Map<String, dynamic>;
return InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (builder) =>
ViewData(
document: document,
id : snapshot.data.docs[index].id,
),
),
);
},
Help me find the correct document id.
Solution 1:[1]
use set() method if you want change many data in doc, set will create new document if not exists or overwrite new data in document
FirebaseFirestore.instance.collection("mytask").doc(widget.id).set({
"title": titleController.text,
"description": descriptionController.text,
"type": type,
"category": category,
"format": format,
});
See more how to add data to cloud firestore
Solution 2:[2]
Can you try the below code by using the snapshot type
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasData &&
snapshot.data.docs.length != 0) {
List<DocumentSnapshot> snap =
snapshot.data.docs;
return ListView.builder(
itemCount: snapshot.data.docs.length,
itemBuilder: (context, index) {
Map<String, dynamic> document = snapshot.data.docs[index]
.data() as Map<String, dynamic>;
return InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (builder) =>
ViewData(
document: document,
id : snap[index].id,
),
),
);
},
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Gejaa |
