In a firebase animated list, how do you put in a conditional statement, or anything else, so that only one set of data in Realtime Database will be displayed? I currently can display all of them in a ListTile but I only want to display a destination whose name is 'Spain' and its description instead of all the database that contains Spain, Italy, USA etc.
class _TestDestinationsState extends State<TestDestinations> {
final destdatabaseref = FirebaseDatabase.instance
.reference()
.child('Database')
.child('Destinations');
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Color(0xFF4D71AC),
elevation: 0,
centerTitle: true,
title: Text('Eh',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w500,
color: Colors.white)),
),
body: SafeArea(
child: FirebaseAnimatedList(
itemBuilder: (BuildContext context, DataSnapshot snapshot,
Animation<double> animation, int index) {
return SingleChildScrollView(
child: Column(
children: [
SizedBox(height: 15),
Padding(
padding: const EdgeInsets.all(8),
child: ListTile(
title: Text(snapshot.value['name'],
style: TextStyle(fontSize: 20)),
subtitle: Text(snapshot.value['description'])),
),
],
),
);
},
query: destdatabaseref,
)),
);
}
}
CodePudding user response:
If we need to only display specific data from FirebaseDatabase
we can use the following logic:
Visibility(
visible: snapshot.value['name'] == 'Spain',
child: ...
),
The complete snippet can be found below:
class _TestDestinationsState extends State<TestDestinations> {
final destdatabaseref = FirebaseDatabase.instance
.reference()
.child('Database')
.child('Destinations');
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Color(0xFF4D71AC),
elevation: 0,
centerTitle: true,
title: Text('Eh',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w500,
color: Colors.white)),
),
body: SafeArea(
child: FirebaseAnimatedList(
itemBuilder: (BuildContext context, DataSnapshot snapshot,
Animation<double> animation, int index) {
return Visibility(
visible: snapshot.value['name'] == 'Spain',
child: SingleChildScrollView(
child: Column(
children: [
SizedBox(height: 15),
Padding(
padding: const EdgeInsets.all(8),
child: ListTile(
title: Text(snapshot.value['name'],
style: TextStyle(fontSize: 20)),
subtitle: Text(snapshot.value['description'])),
),
],
),
),
);
},
query: destdatabaseref,
)),
);
}
}
However a much better solution, would be to retrieve only specific data based on the filter, which can be done by filtering our query to FirebaseDatabase
as follows:
final destdatabaseref = FirebaseDatabase.instance
.reference()
.child('Database')
.child('Destinations')
.orderByChild('name')
.equalTo('Spain');