Last active
July 27, 2022 17:37
-
-
Save branflake2267/e3803f37ca4f6621f1214f948225031c to your computer and use it in GitHub Desktop.
Flutter - Firebase Realtime Database Persistence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
import 'package:firebase_database/firebase_database.dart'; | |
import 'package:intl/intl.dart'; | |
class Database { | |
static Future<String> createMountain() async { | |
String accountKey = await _getAccountKey(); | |
var mountain = <String, dynamic>{ | |
'name' : '', | |
'created': _getDateNow(), | |
}; | |
DatabaseReference reference = FirebaseDatabase.instance | |
.reference() | |
.child("accounts") | |
.child(accountKey) | |
.child("mountains") | |
.push(); | |
reference.set(mountain); | |
return reference.key; | |
} | |
static Future<void> saveName(String mountainKey, String name) async { | |
String accountKey = await _getAccountKey(); | |
return FirebaseDatabase.instance | |
.reference() | |
.child("accounts") | |
.child(accountKey) | |
.child("mountains") | |
.child(mountainKey) | |
.child('name') | |
.set(name); | |
} | |
static Future<StreamSubscription<Event>> getNameStream(String mountainKey, | |
void onData(String name)) async { | |
String accountKey = await _getAccountKey(); | |
StreamSubscription<Event> subscription = FirebaseDatabase.instance | |
.reference() | |
.child("accounts") | |
.child(accountKey) | |
.child("mountains") | |
.child(mountainKey) | |
.child("name") | |
.onValue | |
.listen((Event event) { | |
String name = event.snapshot.value as String; | |
if (name == null) { | |
name = ""; | |
} | |
onData(name); | |
}); | |
return subscription; | |
} | |
static Future<Query> queryMountains() async { | |
String accountKey = await _getAccountKey(); | |
return FirebaseDatabase.instance | |
.reference() | |
.child("accounts") | |
.child(accountKey) | |
.child("mountains") | |
.orderByChild("name"); | |
} | |
} | |
Future<String> _getAccountKey() async { | |
return '12345678'; | |
} | |
/// requires: intl: ^0.15.2 | |
String _getDateNow() { | |
var now = new DateTime.now(); | |
var formatter = new DateFormat('yyyy-MM-dd HH:mm:ss'); | |
return formatter.format(now); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
import 'package:flutter/material.dart'; | |
import 'package:flutter_firebase/database.dart'; | |
class EditMountianPage extends StatefulWidget { | |
static String routeName = '/edit_mountain'; | |
final String mountainKey; | |
EditMountianPage({Key key, this.mountainKey}) : super(key: key); | |
@override | |
_EditMountianPageState createState() => new _EditMountianPageState(); | |
} | |
class _EditMountianPageState extends State<EditMountianPage> { | |
final _nameFieldTextController = new TextEditingController(); | |
StreamSubscription _subscriptionName; | |
@override | |
void initState() { | |
_nameFieldTextController.clear(); | |
Database.getNameStream(widget.mountainKey, _updateName) | |
.then((StreamSubscription s) => _subscriptionName = s); | |
super.initState(); | |
} | |
@override | |
void dispose() { | |
if (_subscriptionName != null) { | |
_subscriptionName.cancel(); | |
} | |
super.dispose(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return new Scaffold( | |
appBar: new AppBar( | |
title: new Text("Edit Mountain"), | |
), | |
body: new ListView( | |
children: <Widget>[ | |
new ListTile( | |
title: new TextField( | |
controller: _nameFieldTextController, | |
decoration: new InputDecoration( | |
icon: new Icon(Icons.edit), | |
labelText: "Mountain Name", | |
hintText: "Enter the mountain name..." | |
), | |
onChanged: (String value) { | |
Database.saveName(widget.mountainKey, value); | |
}, | |
), | |
) | |
], | |
), | |
); | |
} | |
void _updateName(String name) { | |
_nameFieldTextController.value = _nameFieldTextController.value.copyWith( | |
text: name, | |
); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:firebase_database/firebase_database.dart'; | |
import 'package:firebase_database/ui/firebase_animated_list.dart'; | |
import 'package:flutter/material.dart'; | |
import 'package:flutter_firebase/database.dart'; | |
import 'package:flutter_firebase/edit_mountain.dart'; | |
void main() => runApp(new MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return new MaterialApp( | |
title: 'Flutter Demo', | |
theme: new ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: new MyHomePage(), | |
routes: <String, WidgetBuilder>{ | |
EditMountianPage.routeName: (context) => new EditMountianPage(), | |
}, | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
@override | |
_MyHomePageState createState() => new _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
Query _query; | |
@override | |
void initState() { | |
Database.queryMountains().then((Query query) { | |
setState(() { | |
_query = query; | |
}); | |
}); | |
super.initState(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
Widget body = new ListView( | |
children: <Widget>[ | |
new ListTile( | |
title: new Text("The list is empty..."), | |
) | |
], | |
); | |
if (_query != null) { | |
body = new FirebaseAnimatedList( | |
query: _query, | |
itemBuilder: ( | |
BuildContext context, | |
DataSnapshot snapshot, | |
Animation<double> animation, | |
int index, | |
) { | |
String mountainKey = snapshot.key; | |
Map map = snapshot.value; | |
String name = map['name'] as String; | |
return new Column( | |
children: <Widget>[ | |
new ListTile( | |
title: new Text('$name'), | |
onTap: () { | |
_edit(mountainKey); | |
}, | |
), | |
new Divider( | |
height: 2.0, | |
), | |
], | |
); | |
}, | |
); | |
} | |
return new Scaffold( | |
appBar: new AppBar( | |
title: new Text("Home"), | |
), | |
body: body, | |
floatingActionButton: new FloatingActionButton( | |
child: new Icon(Icons.add), | |
onPressed: () { | |
_createMountain(); | |
}, | |
), | |
); | |
} | |
void _createMountain() { | |
Database.createMountain().then((String mountainKey) { | |
_edit(mountainKey); | |
}); | |
} | |
void _edit(String mountainKey) { | |
var route = new MaterialPageRoute( | |
builder: (context) => new EditMountianPage(mountainKey: mountainKey), | |
); | |
Navigator.of(context).push(route); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
name: flutter_firebase | |
description: A new Flutter application. | |
dependencies: | |
flutter: | |
sdk: flutter | |
# The following adds the Cupertino Icons font to your application. | |
# Use with the CupertinoIcons class for iOS style icons. | |
cupertino_icons: ^0.1.0 | |
cloud_firestore: ^0.6.2 | |
firebase_database: ^0.4.5 | |
intl: ^0.15.2 | |
dev_dependencies: | |
flutter_test: | |
sdk: flutter | |
# For information on the generic Dart part of this file, see the | |
# following page: https://www.dartlang.org/tools/pub/pubspec | |
# The following section is specific to Flutter. | |
flutter: | |
# The following line ensures that the Material Icons font is | |
# included with your application, so that you can use the icons in | |
# the material Icons class. | |
uses-material-design: true | |
# To add assets to your application, add an assets section, like this: | |
# assets: | |
# - images/a_dot_burr.jpeg | |
# - images/a_dot_ham.jpeg | |
# An image asset can refer to one or more resolution-specific "variants", see | |
# https://flutter.io/assets-and-images/#resolution-aware. | |
# For details regarding adding assets from package dependencies, see | |
# https://flutter.io/assets-and-images/#from-packages | |
# To add custom fonts to your application, add a fonts section here, | |
# in this "flutter" section. Each entry in this list should have a | |
# "family" key with the font family name, and a "fonts" key with a | |
# list giving the asset and other descriptors for the font. For | |
# example: | |
# fonts: | |
# - family: Schyler | |
# fonts: | |
# - asset: fonts/Schyler-Regular.ttf | |
# - asset: fonts/Schyler-Italic.ttf | |
# style: italic | |
# - family: Trajan Pro | |
# fonts: | |
# - asset: fonts/TrajanPro.ttf | |
# - asset: fonts/TrajanPro_Bold.ttf | |
# weight: 700 | |
# | |
# For details regarding fonts from package dependencies, | |
# see https://flutter.io/custom-fonts/#from-packages |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nicely explained