Simple DB Flutter

Simple Flutter and Firebase connection with CURD oparation

main.dart

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:fireabase_db_curd/add_data_page.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: FirebaseOptions(
      apiKey: "apikey",
      appId: "appid",
      messagingSenderId: "",
      projectId: "projectid"
  ));

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: AddDataPage(),
    );
  }
}

AddDataPage.dart

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'view_data_page.dart';
class AddDataPage extends StatefulWidget {
  @override
  _AddDataPageState createState() => _AddDataPageState();
}

class _AddDataPageState extends State<AddDataPage> {
  final TextEditingController nameController = TextEditingController();
  final TextEditingController ageController = TextEditingController();
  final FirebaseFirestore _firestore = FirebaseFirestore.instance;


  void saveData() async {
    if (nameController.text.isNotEmpty && ageController.text.isNotEmpty) {
      await _firestore.collection('users').add({
        'name': nameController.text,
        'age': int.parse(ageController.text),
      });
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text('Data Saved!')));
      nameController.clear();
      ageController.clear();
    } else {
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text('Please fill all fields!')));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Add Data')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              controller: nameController,
              decoration: InputDecoration(labelText: 'Name'),
            ),
            TextField(
              controller: ageController,
              decoration: InputDecoration(labelText: 'Age'),
              keyboardType: TextInputType.number,
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: saveData,
              child: Text('Save'),
            ),
            ElevatedButton(
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => ViewDataPage()),
                );
              },
              child: Text('View Data'),
            ),
          ],
        ),
      ),
    );
  }
}

view_data_page.dart

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class ViewDataPage extends StatelessWidget {
  final FirebaseFirestore _firestore = FirebaseFirestore.instance;

  void deleteData(String id) async {
    await _firestore.collection('users').doc(id).delete();
    SnackBar(content: Text("Data Deleted..!"),);
  }

  void updateData(String id, String newName, int newAge) async {
    await _firestore.collection('users').doc(id).update({
      'name': newName,
      'age': newAge,
    });
    SnackBar(content: Text("Data Updated..!"),);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('View Data')),
      body: StreamBuilder(
        stream: _firestore.collection('users').snapshots(),
        builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
          if (!snapshot.hasData) {
            return Center(child: CircularProgressIndicator());
          }
          return ListView(
            children: snapshot.data!.docs.map((doc) {
              final data = doc.data() as Map<String, dynamic>;
              final name = data['name'];
              final age = data['age'];
              return Card(
                margin: EdgeInsets.all(10),
                child: ListTile(
                  title: Text('Name: $name'),
                  subtitle: Text('Age: $age'),
                  trailing: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      IconButton(
                        icon: Icon(Icons.edit),
                        onPressed: () {
                          TextEditingController nameController =
                              TextEditingController(text: name);
                          TextEditingController ageController =
                              TextEditingController(text: age.toString());
                          showDialog(
                            context: context,
                            builder: (context) {
                              return AlertDialog(
                                title: Text('Update Data'),
                                content: Column(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    TextField(
                                      controller: nameController,
                                      decoration:
                                          InputDecoration(labelText: 'Name'),
                                    ),
                                    TextField(
                                      controller: ageController,
                                      decoration:
                                          InputDecoration(labelText: 'Age'),
                                      keyboardType: TextInputType.number,
                                    ),
                                  ],
                                ),
                                actions: [
                                  ElevatedButton(
                                    onPressed: () {
                                      updateData(
                                        doc.id,
                                        nameController.text,
                                        int.parse(ageController.text),
                                      );
                                      Navigator.pop(context);
                                    },
                                    child: Text('Update'),
                                  ),
                                ],
                              );
                            },
                          );
                        },
                      ),
                      IconButton(
                        icon: Icon(Icons.delete),
                        onPressed: () {
                          deleteData(doc.id);
                        },
                      ),
                    ],
                  ),
                ),
              );
            }).toList(),
          );
        },
      ),
    );
  }
}

flutter pub add firebase_core
flutter pub add firebase_database
flutter pub add cloud_firestore

terminal run above commands

And what is your question?
Please format code as code to make it easier to read.

To improve my Flutter app with Firebase CRUD operations, I would first make sure to use the correct straight quotation marks (" or ') instead of typographic ones to avoid syntax issues. I would then structure my code better by breaking it down into smaller, modular components, such as separating the data display and form fields into different widgets. To create a smoother user experience, I would handle errors gracefully with try-catch blocks and display appropriate error messages using SnackBar. For updating data efficiently, I would use setState directly in the list, so the UI updates without reloading the entire page. I would also consider using ListView.builder for dynamic lists to improve performance. Additionally, I would ensure input validation to avoid invalid data entries and configure Firebase security rules to protect user data. These improvements would make my code cleaner, more maintainable, and provide a better user experience.

There is a much better little method than this.

Before using these lib and run it

flutter pub add firebase_core
flutter pub add firebase_database
flutter pub add cloud_firestore

The code is below.

Data Insert Function

 final TextEditingController nameController = TextEditingController();
  final TextEditingController ageController = TextEditingController();

  final FirebaseFirestore db_fire = FirebaseFirestore.instance;
 void savedata() async {
    String name = nameController.text;
    int age = int.parse(ageController.text);

    if (name.isNotEmpty && age > 0) {
      await db_fire.collection('TestDBV4').add({'Name': name, 'Age': age});

      nameController.clear();
      ageController.clear();

      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
        content: Text(
          "Data Insert Successfully..!",
          style: TextStyle(color: Colors.white),
        ),
        backgroundColor: Colors.green,
      ));
    } else {
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
        content: Text(
          "Insert Error.!",
          style: TextStyle(color: Colors.white),
        ),
        backgroundColor: Colors.red,
      ));
    }
  }

Data Update Function

 void update(String id, String current_name, int current_age) {
    nameController.text = current_name;
    ageController.text = current_age.toString();

    showDialog(
        context: context,
        builder: (context) => AlertDialog(
              title: const Text("Update"),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  TextField(
                    controller: nameController,
                    decoration: const InputDecoration(labelText: "Name"),
                  ),
                  TextField(
                    controller: ageController,
                    decoration: const InputDecoration(labelText: "Age"),
                    keyboardType: TextInputType.number,
                  ),
                ],
              ),
              actions: [
                TextButton(
                    onPressed: () {
                      nameController.clear();
                      ageController.clear();
                      Navigator.pop(context);
                    },
                    child: const Text("Cancel")),
                TextButton(
                  onPressed: () async {
                    String updateName = nameController.text;
                    int updateAge = int.parse(ageController.text);

                    if (updateName.isNotEmpty && updateAge > 0) {
                      await db_fire
                          .collection('TestDBV4')
                          .doc(id)
                          .update({'Name': updateName, 'Age': updateAge});

                      nameController.clear();
                      ageController.clear();
                      Navigator.pop(context);

                      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
                        content: Text(
                          "Update Successfully..!",
                          style: TextStyle(color: Colors.white),
                        ),
                        backgroundColor: Colors.green,
                      ));
                    } else {
                      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
                        content: Text("Error update",
                            style: TextStyle(color: Colors.white)),
                        backgroundColor: Colors.red,
                      ));
                    }
                  },
                  child: const Text("Update"),
                ),
              ],
            ));
  }

Desing

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("FireBase V04",
            style: TextStyle(color: Colors.black, fontSize: 20.0)),
        backgroundColor: Colors.orange,
        centerTitle: true,
      ),
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          children: [
            TextField(
              controller: nameController,
              decoration: const InputDecoration(labelText: "Enter Name"),
            ),
            TextField(
              controller: ageController,
              decoration: const InputDecoration(labelText: "Enter Age"),
              keyboardType: TextInputType.number,
            ),
            const SizedBox(
              height: 20.0,
            ),
            ElevatedButton(onPressed: savedata, child: const Text("Submit")),
            const SizedBox(
              height: 20.0,
            ),
            Expanded(
              child: StreamBuilder(
                  stream: db_fire.collection('TestDBV4').snapshots(),
                  builder: (context, snapshot) {
                    if (!snapshot.hasData) {
                      return const Center(
                        child: CircularProgressIndicator(),
                      );
                    }

                    return ListView.builder(
                        itemCount: snapshot.data!.docs.length,
                        itemBuilder: (context, index) {
                          var doc = snapshot.data!.docs[index];
                          var id = doc.id;
                          var name = doc['Name'];
                          var age = doc['Age'];

                          return Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Container(
                              color: Colors.black12,
                              child: ListTile(
                                title: Text("Your Name: $name"),
                                subtitle: Text("Your Age: $age"),
                                trailing: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    IconButton(
                                      onPressed: () => update(id, name, age),
                                      icon: const Icon(
                                        CupertinoIcons.pencil,
                                        size: 25.0,
                                      ),
                                      color: Colors.green,
                                    ),
                                    IconButton(
                                      onPressed: () {
                                        db_fire
                                            .collection('TestDBV4')
                                            .doc(id)
                                            .delete();

                                        ScaffoldMessenger.of(context)
                                            .showSnackBar(const SnackBar(
                                          content: Text(
                                            "Data Delete Successfully..!",
                                            style: TextStyle(
                                                color: Colors.white,
                                                fontSize: 15.0),
                                          ),
                                          backgroundColor: Colors.purple,
                                        ));
                                      },
                                      icon: const Icon(
                                        Icons.delete,
                                        size: 25.0,
                                      ),
                                      color: Colors.red,
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          );
                        });
                  }),
            ),
          ],
        ),
      ),
    );
  }
}

Not sure what is that post about @Oliver but I reformatted the code for you. You should use three quotations marks (backticks) (on the same key as tilde ~) to format your code:

```dart
your code here
```
3 Likes