Advertisement
fahimkamal63

Firebase create, update, delete Flutter Updated

Jan 12th, 2022
1,703
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 6.47 KB | None | 0 0
  1. import 'package:cloud_firestore/cloud_firestore.dart';
  2. import 'package:flutter/material.dart';
  3.  
  4. class DatabaseBasic extends StatefulWidget {
  5.   const DatabaseBasic({Key? key}) : super(key: key);
  6.  
  7.   @override
  8.   _DatabaseBasicState createState() => _DatabaseBasicState();
  9. }
  10.  
  11. class _DatabaseBasicState extends State<DatabaseBasic> {
  12.  
  13.   TextEditingController name = TextEditingController();
  14.   TextEditingController email = TextEditingController();
  15.  
  16.   create() async {
  17.     try{
  18.       await FirebaseFirestore.instance.collection('user').doc(email.text).set(
  19.         {
  20.           'name': name.text,
  21.           'email': email.text
  22.         }
  23.       );
  24.     } catch(e){
  25.       print(e);
  26.     }
  27.   }
  28.  
  29.   update() async {
  30.     try{
  31.       await FirebaseFirestore.instance.collection('user').doc(email.text).update({
  32.         'name': name.text
  33.       });
  34.  
  35.     } catch(e){
  36.       print(e);
  37.     }
  38.   }
  39.  
  40.   delete() async {
  41.     try{
  42.       await FirebaseFirestore.instance.collection('user').doc(email.text).delete();
  43.     } catch(e){
  44.       print(e);
  45.     }
  46.   }
  47.  
  48.   @override
  49.   Widget build(BuildContext context) {
  50.     return Scaffold(
  51.       appBar: AppBar(
  52.         title: Text("Database Basic"),
  53.         centerTitle: true,
  54.       ),
  55.       body: Padding(
  56.         padding: const EdgeInsets.all(10),
  57.         child: Column(
  58.           children: [
  59.             _customTextField(name, "Name"),
  60.             SizedBox(height: 10,),
  61.             _customTextField(email, "Email"),
  62.             SizedBox(height: 10,),
  63.             Row(
  64.               mainAxisAlignment: MainAxisAlignment.center,
  65.               children: [
  66.                 _customElevatedButton(onPressed: create, btnLabel: "Create"),
  67.                 SizedBox(width: 10,),
  68.                 _customElevatedButton(onPressed: update, btnLabel: "Update"),
  69.                 SizedBox(width: 10,),
  70.                 _customElevatedButton(onPressed: delete, btnLabel: "Delete"),
  71.               ],
  72.             ),
  73.             SizedBox(height: 10,),
  74.             Expanded(
  75.               child: Container(
  76.                 child: StreamBuilder(
  77.                   stream: FirebaseFirestore.instance.collection('user').snapshots(),
  78.                   builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
  79.                     if(snapshot.hasData){
  80.                       return ListView.builder(
  81.                         shrinkWrap: true,
  82.                         physics: BouncingScrollPhysics(),
  83.                         primary: true,
  84.                         itemCount: snapshot.data!.docs.length,
  85.                         itemBuilder: (context, index){
  86.                           QueryDocumentSnapshot networkData = snapshot.data!.docs[index];
  87.                           return Card(
  88.                             child: ListTile(
  89.                               onLongPress: (){
  90.                                 setState(() {
  91.                                   name.text = networkData['name'];
  92.                                   email.text = networkData['email'];
  93.                                 });
  94.                               },
  95.                               title: Text(networkData['name']),
  96.                               subtitle: Text(networkData['email']),
  97.                               trailing: IconButton(
  98.                                 onPressed: (){
  99.                                   showDialog(
  100.                                     context: context,
  101.                                     builder: (context){
  102.                                       return AlertDialog(
  103.                                         title: Text("Confirm!!!"),
  104.                                         content: Text("Are you sure you?"),
  105.                                         actions: [
  106.                                           ElevatedButton(
  107.                                             onPressed: (){
  108.                                               name.text = networkData['name'];
  109.                                               email.text = networkData['email'];
  110.                                               delete();
  111.                                               name.clear();
  112.                                               email.clear();
  113.                                               Navigator.pop(context);
  114.                                             },
  115.                                             child: Text("Yes")),
  116.                                           ElevatedButton(
  117.                                             onPressed: (){
  118.                                               Navigator.pop(context);
  119.                                             },
  120.                                             child: Text("No")),
  121.                                         ],
  122.                                       );
  123.                                     }
  124.                                   );
  125.                                 },
  126.                                   icon: Icon(Icons.delete, color: Colors.red,),
  127.                               ),
  128.                               // leading: Text(networkData['test']),
  129.                             ),
  130.                           );
  131.                         }
  132.                       );
  133.                     }
  134.                     return const Center(child: CircularProgressIndicator());
  135.                   }
  136.                 ),
  137.               ),
  138.             ),
  139.           ],
  140.         ),
  141.       ),
  142.     );
  143.   }
  144.  
  145.   Widget _customTextField(TextEditingController controller, String label){
  146.     return TextField(
  147.       controller: controller,
  148.       decoration: InputDecoration(
  149.         label: Text(label),
  150.         border: OutlineInputBorder(
  151.             borderSide: BorderSide(color: Colors.red, width: 2),
  152.             borderRadius: BorderRadius.circular(15)
  153.         ),
  154.         enabledBorder: OutlineInputBorder(
  155.             borderSide: BorderSide(color: Colors.red, width: 2),
  156.             borderRadius: BorderRadius.circular(15)
  157.         ),
  158.         focusedBorder: OutlineInputBorder(
  159.             borderSide: BorderSide(color: Colors.red, width: 2),
  160.             borderRadius: BorderRadius.circular(15)
  161.         ),
  162.       ),
  163.     );
  164.   }
  165.  
  166.   /// [onPressed] : Give the function that needs to call on pressing the button.
  167.   ///
  168.   /// [btnLabel] : Give the name of the Button.
  169.   Widget _customElevatedButton({required VoidCallback? onPressed, required String btnLabel})  {
  170.     return ElevatedButton(
  171.       onPressed: (){
  172.         onPressed!();
  173.         setState(() {
  174.           name.clear();
  175.           email.clear();
  176.         });
  177.       },
  178.       child: Text(btnLabel),
  179.     );
  180.   }
  181. }
  182.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement