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 {
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 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.