Here's a step-by-step guide to creating a complete Flutter application using Firebase Realtime Database:
Set up Firebase
Create a new Flutter project using your preferred IDE.
Set up Firebase in your project by following the instructions in the Firebase documentation. This includes creating a Firebase project, adding the necessary configuration files, and enabling the Realtime Database service.
Add Dependencies
Open your project's
pubspec.yamlfile and add the following dependencies:
dependencies:
flutter:
sdk: flutter
firebase_core: ^1.4.0
firebase_database: ^10.1.0
Save the file and run
flutter pub getto fetch the dependencies.
Update the main.dart file
Replace the code in your
main.dartfile with the following code:
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_database/firebase_database.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(FirebaseApp());
}
class FirebaseApp extends StatefulWidget {
@override
_FirebaseAppState createState() => _FirebaseAppState();
}
class _FirebaseAppState extends State<FirebaseApp> {
final databaseReference = FirebaseDatabase.instance.reference();
String _message = '';
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Firebase Realtime Database'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Message from Firebase:',
),
Text(_message),
ElevatedButton(
child: Text('Fetch Data'),
onPressed: () {
_fetchDataFromFirebase();
},
),
ElevatedButton(
child: Text('Save Data'),
onPressed: () {
_saveDataToFirebase();
},
),
],
),
),
),
);
}
Future<void> _fetchDataFromFirebase() async {
final snapshot = await databaseReference.child('messages').once();
final value = snapshot.value as String;
setState(() {
_message = value;
});
}
Future<void> _saveDataToFirebase() async {
await databaseReference.child('messages').set('Hello from Flutter!');
}
}Run the Application
Ensure you have an emulator or a physical device connected.
Run the app using
flutter runin the terminal or by clicking the "Run" button in your IDE.

No comments:
Post a Comment