Here, we will see how to add data to firestore collection. We have to do the below things
- create a collection
- using the add function on the collection
- use map data for add function
First we get collection reference like below
await FirebaseFirestore.instance.collection("people");
Then we add the add() to it.
await FirebaseFirestore.instance.collection("people").add({
});
Inside this we need to map or json format data.
"name":"Dastagir Ahme",
"age":34,
"job":"freelance",
"country":"Bangladesh",
"addTime":Timestamp.now()
Let’s take a look at our function that will add data to the collection.
_incrementCounter() async {
await collection.add({
"name":"Dastagir Ahme",
"age":34,
"job":"freelance",
"country":"Bangladesh",
"addTime":Timestamp.now()
});
var allDocuments = await collection.get();
var num = allDocuments.size;
setState(() {
_counter = num;
});
}
This will get called from a button click. Button click would trigger the adding data mechanism.
Later, we get the reference of all the documents so that we can get the total number of documents in the collection.
We simply call the size field of it.
Let’s see the complete code
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 {
await collection.add({
"name":"Dastagir Ahme",
"age":34,
"job":"freelance",
"country":"Bangladesh",
"addTime":Timestamp.now()
});
var allDocuments = await collection.get();
var num = allDocuments.size;
setState(() {
_counter = num;
});
}
@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.
);
}
}