Make sure you have you firebase project set up. We will use firestore collection() and set() to set data to firestore collection.
Since we need to use the set(), we need document ID. For document ID, we need to get all the documents.
First we get all the documents using get() and then we access the first and last document id.
var allDocs = await collection.get();
var docID = allDocs.docs.last.id;
You see from the code that we get all the documents using collection.get() and then we use the docs field to access the last document id, you may also get first document id.
And then based on the document ID, we can call the set() function.
await collection.doc(docID).set({
"name":"Dastagir Ahmed",
"age":60,
"job":"programmer",
"country":"Bangladesh",
"addTime":Timestamp.now()
});
import 'dart:math';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'firebase_options.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
var collection = FirebaseFirestore.instance.collection("people");
_incrementCounter() async {
var allDocs = await collection.get();
var docID = allDocs.docs.last.id;
await collection.doc(docID).set({
"name":"Dastagir Ahmed",
"age":60,
"job":"programmer",
"country":"Bangladesh",
"addTime":Timestamp.now()
});
setState(() {
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}