Reputation: 905
I'm using StreamBuilder to fetch the data from firebase realtime database(which is frequently changed by me.) So I want my ListView to update the View accordingly. But what it is doing suppose I have 3 data and I've added one more then is showing all 4 data below the previous 3 data(i.e 7) untill I reopen the page.
Here is my code:
Widget build(BuildContext context) {
var ref = FirebaseDatabase.instance.reference().child('Orders');
List<PendingOrderLoader> pendingOrderLoaderList1 = [];
return Scaffold(
body: SafeArea(
child: Column(
children: <Widget>[
Container(
height: 200,
child: StreamBuilder(
stream: FirebaseDatabase.instance.reference().child('Orders').onValue,
builder: (BuildContext context, snapshot){
if (snapshot.hasData && !snapshot.hasError && snapshot.data.snapshot.value!=null) {
DataSnapshot snapshot1 = snapshot.data.snapshot;
final key = snapshot1.value.keys;
for(var i in key)
{
print(i);
PendingOrderLoader pendingOrderLoader1 = new PendingOrderLoader(
snapshot1.value[i]['OrderID'],
snapshot1.value[i]['Date'],
snapshot1.value[i]['Time'],
);
pendingOrderLoaderList1.add(pendingOrderLoader1);
}
return snapshot.data.snapshot.value == null
? SizedBox()
: ListView.builder(
scrollDirection: Axis.vertical,
itemCount: pendingOrderLoaderList1.length,
itemBuilder: (context, index) {
return Text(" "+
pendingOrderLoaderList1[index].OrderID
);
},
);
} else {
return Center(child: CircularProgressIndicator());
}
}
),
)
],
)),
);
}
Earlier there were 3 data and after deleting 1 it is showing new data just below it. I want it to show only new data.
Upvotes: 3
Views: 2058
Reputation: 2539
Define this list
List pendingOrderLoaderList1 = [];
inside the builder after receiving the data
like this:
Widget build(BuildContext context) {
var ref = FirebaseDatabase.instance.reference().child('Orders');
return Scaffold(
body: SafeArea(
child: Column(
children: <Widget>[
Container(
height: 200,
child: StreamBuilder(
stream: FirebaseDatabase.instance.reference().child('Orders').onValue,
builder: (BuildContext context, snapshot){
if (snapshot.hasData && !snapshot.hasError && snapshot.data.snapshot.value!=null) {
DataSnapshot snapshot1 = snapshot.data.snapshot;
List<PendingOrderLoader> pendingOrderLoaderList1 = [];
final key = snapshot1.value.keys;
for(var i in key)
{
print(i);
PendingOrderLoader pendingOrderLoader1 = new PendingOrderLoader(
snapshot1.value[i]['OrderID'],
snapshot1.value[i]['Date'],
snapshot1.value[i]['Time'],
);
pendingOrderLoaderList1.add(pendingOrderLoader1);
}
return snapshot.data.snapshot.value == null
? SizedBox()
: ListView.builder(
scrollDirection: Axis.vertical,
itemCount: pendingOrderLoaderList1.length,
itemBuilder: (context, index) {
return Text(" "+
pendingOrderLoaderList1[index].OrderID
);
},
);
} else {
return Center(child: CircularProgressIndicator());
}
}
),
)
],
)),
);
}
Upvotes: 3