Last active
July 31, 2021 14:56
-
-
Save manofi21/8d1025779c294f7f10d6ce48145dafc6 to your computer and use it in GitHub Desktop.
realtime database syntax in flutter
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
// declaration and inisialitation variable | |
int _counter; | |
DatabaseReference _counterRef; | |
DatabaseReference _messagesRef; | |
StreamSubscription<Event> _counterSubscription; | |
StreamSubscription<Event> _messagesSubscription; | |
bool _anchorToBottom = false; | |
String _kTestKey = 'Hello'; | |
String _kTestValue = 'world!'; | |
DatabaseError _error; |
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
@override | |
void initState() { | |
super.initState(); | |
/*** Create variable deafult in realtime database ***/ | |
_counterRef = FirebaseDatabase.instance.reference().child('counter'); | |
/*** Create the FirebaseDatabase Object ***/ | |
final FirebaseDatabase database = FirebaseDatabase(); | |
/*** Create new table in realtime database ***/ | |
_messagesRef = database.reference().child('messages'); | |
/*** Calling the variable in realtime. Get the value and print it ***/ | |
database.reference().child('counter').once().then((DataSnapshot snapshot) { | |
print('Connected to second database and read ${snapshot.value}'); | |
}); | |
/*** Attempts to sets the database persistence to [enabled]. ***/ | |
database.setPersistenceEnabled(true); | |
/*** Attempts to set the size of the persistence cache. ***/ | |
database.setPersistenceCacheSizeBytes(10000000); | |
/*** To set automatic download and kept in sync ***/ | |
_counterRef.keepSynced(true); | |
/*** fill the _counterSubscription to changes _counter's variable ***/ | |
_counterSubscription = _counterRef.onValue.listen((Event event) { | |
setState(() { | |
_error = null; | |
_counter = event.snapshot.value ?? 0; | |
}); | |
}, onError: (Object o) { | |
final DatabaseError error = o; | |
setState(() { | |
_error = error; | |
}); | |
}); | |
/*** fill the _messageSubscription to print value after add new data in table and limit 10 ***/ | |
_messagesSubscription = | |
_messagesRef.limitToLast(10).onChildAdded.listen((Event event) { | |
print('Child added: ${event.snapshot.value}'); | |
}, onError: (Object o) { | |
final DatabaseError error = o; | |
print('Error: ${error.code} ${error.message}'); | |
}); | |
} |
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
@override | |
void dispose() { | |
super.dispose(); | |
_messagesSubscription.cancel(); | |
_counterSubscription.cancel(); | |
} | |
Future<void> _increment() async { | |
/*** Updating values in _counterRef with realtime ***/ | |
/*** runTransaction Performs an optimistic-concurrency transactional update to the data at this Firebase Database location. ***/ | |
final TransactionResult transactionResult = | |
await _counterRef.runTransaction((MutableData mutableData) async { | |
mutableData.value = (mutableData.value ?? 0) + 1; | |
return mutableData; | |
}); | |
/*** mutableData will be a value's variable from _conterRef(DatabaseReference). Then add 1 to current value ***/ | |
if (transactionResult.committed) { | |
_messagesRef.push().set(<String, String>{ | |
_kTestKey: '$_kTestValue ${transactionResult.dataSnapshot.value}' | |
}); | |
} else { | |
print('Transaction not committed.'); | |
if (transactionResult.error != null) { | |
print(transactionResult.error.message); | |
} | |
} | |
/*** if the update true / committed, the system will send new data to add in table ***/ | |
} |
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
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: const Text('Flutter Database Example'), | |
), | |
body: Column( | |
children: <Widget>[ | |
/*** Text to show _counter's value ***/ | |
Flexible( | |
child: Center( | |
child: _error == null | |
? Text( | |
'Button tapped $_counter time${_counter == 1 ? '' : 's'}.\n\n' | |
'This includes all devices, ever.', | |
) | |
: Text( | |
'Error retrieving button tap count:\n${_error.message}', | |
), | |
), | |
), | |
/*** CheckBox for changes position List to under layout ***/ | |
ListTile( | |
leading: Checkbox( | |
onChanged: (bool value) { | |
setState(() { | |
_anchorToBottom = value; | |
}); | |
}, | |
value: _anchorToBottom, | |
), | |
title: const Text('Anchor to bottom'), | |
), | |
/*** FirebaseAnimatedList to create List with firebase reference with animation***/ | |
Flexible( | |
child: FirebaseAnimatedList( | |
key: ValueKey<bool>(_anchorToBottom), | |
query: _messagesRef, | |
reverse: _anchorToBottom, | |
sort: _anchorToBottom | |
? (DataSnapshot a, DataSnapshot b) => b.key.compareTo(a.key) | |
: null, | |
itemBuilder: (BuildContext context, DataSnapshot snapshot, | |
Animation<double> animation, int index) { | |
return SizeTransition( | |
sizeFactor: animation, | |
child: ListTile( | |
trailing: IconButton( | |
onPressed: () => | |
_messagesRef.child(snapshot.key).remove(), | |
icon: Icon(Icons.delete), | |
), | |
title: Text( | |
"$index: ${snapshot.value.toString()}", | |
), | |
), | |
); | |
}, | |
), | |
), | |
], | |
), | |
/*** Call increment action ***/ | |
floatingActionButton: FloatingActionButton( | |
onPressed: _increment, | |
tooltip: 'Increment', | |
child: const Icon(Icons.add), | |
), | |
); | |
} |
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
class MyHomePage extends StatefulWidget { | |
@override | |
_MyHomePageState createState() => _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
int _counter; | |
DatabaseReference _counterRef; | |
DatabaseReference _messagesRef; | |
StreamSubscription<Event> _counterSubscription; | |
StreamSubscription<Event> _messagesSubscription; | |
bool _anchorToBottom = false; | |
String _kTestKey = 'Hello'; | |
String _kTestValue = 'world!'; | |
DatabaseError _error; | |
@override | |
void initState() { | |
super.initState(); | |
_counterRef = FirebaseDatabase.instance.reference().child('counter'); | |
final FirebaseDatabase database = FirebaseDatabase(); | |
_messagesRef = database.reference().child('messages'); | |
database.reference().child('counter').once().then((DataSnapshot snapshot) { | |
print('Connected to second database and read ${snapshot.value}'); | |
}); | |
database.setPersistenceEnabled(true); | |
database.setPersistenceCacheSizeBytes(10000000); | |
_counterRef.keepSynced(true); | |
_counterSubscription = _counterRef.onValue.listen((Event event) { | |
setState(() { | |
_error = null; | |
_counter = event.snapshot.value ?? 0; | |
}); | |
}, onError: (Object o) { | |
final DatabaseError error = o; | |
setState(() { | |
_error = error; | |
}); | |
}); | |
_messagesSubscription = | |
_messagesRef.limitToLast(10).onChildAdded.listen((Event event) { | |
print('Child added: ${event.snapshot.value}'); | |
}, onError: (Object o) { | |
final DatabaseError error = o; | |
print('Error: ${error.code} ${error.message}'); | |
}); | |
} | |
@override | |
void dispose() { | |
super.dispose(); | |
_messagesSubscription.cancel(); | |
_counterSubscription.cancel(); | |
} | |
Future<void> _increment() async { | |
// Increment counter in transaction. | |
final TransactionResult transactionResult = | |
await _counterRef.runTransaction((MutableData mutableData) async { | |
mutableData.value = (mutableData.value ?? 0) + 1; | |
return mutableData; | |
}); | |
if (transactionResult.committed) { | |
_messagesRef.push().set(<String, String>{ | |
_kTestKey: '$_kTestValue ${transactionResult.dataSnapshot.value}' | |
}); | |
} else { | |
print('Transaction not committed.'); | |
if (transactionResult.error != null) { | |
print(transactionResult.error.message); | |
} | |
} | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: const Text('Flutter Database Example'), | |
), | |
body: Column( | |
children: <Widget>[ | |
Flexible( | |
child: Center( | |
child: _error == null | |
? Text( | |
'Button tapped $_counter time${_counter == 1 ? '' : 's'}.\n\n' | |
'This includes all devices, ever.', | |
) | |
: Text( | |
'Error retrieving button tap count:\n${_error.message}', | |
), | |
), | |
), | |
ListTile( | |
leading: Checkbox( | |
onChanged: (bool value) { | |
setState(() { | |
_anchorToBottom = value; | |
}); | |
}, | |
value: _anchorToBottom, | |
), | |
title: const Text('Anchor to bottom'), | |
), | |
Flexible( | |
child: FirebaseAnimatedList( | |
key: ValueKey<bool>(_anchorToBottom), | |
query: _messagesRef, | |
reverse: _anchorToBottom, | |
sort: _anchorToBottom | |
? (DataSnapshot a, DataSnapshot b) => b.key.compareTo(a.key) | |
: null, | |
itemBuilder: (BuildContext context, DataSnapshot snapshot, | |
Animation<double> animation, int index) { | |
return SizeTransition( | |
sizeFactor: animation, | |
child: ListTile( | |
trailing: IconButton( | |
onPressed: () => | |
_messagesRef.child(snapshot.key).remove(), | |
icon: Icon(Icons.delete), | |
), | |
title: Text( | |
"$index: ${snapshot.value.toString()}", | |
), | |
), | |
); | |
}, | |
), | |
), | |
], | |
), | |
floatingActionButton: FloatingActionButton( | |
onPressed: _increment, | |
tooltip: 'Increment', | |
child: const Icon(Icons.add), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment