I have this application that needs a pull to refresh functionality, so I placed the StreamBuilder Widget inside the RefreshIndicator Widget, but I don't know how to manually refresh the StreamBuilder when the onRefreshed event is triggered.
1 Answer. Declare a StreamController with broadcast , then set a friendly name to the Stream of this StreamController , then everytime you want to rebuild the wraped widget (the child of the StreamBuilder just use the sink property of the StreamController to add a new value that will trigger the StreamBuilder .
To use StreamBuilder , you need to call the constructor below. Basically, you need to create a Stream and pass it as the stream argument. Then, you have to pass an AsyncWidgetBuilder which can be used to build the widget based on the snapshots of the Stream .
Pull to refresh (swipe to refresh) feature can be implemented in flutter using RefreshIndicator widget. Pull (swipe) to refresh feature lets the user refresh current data or fetch updated data from the server by pulling down on a list.
Having the stream
as a state variable
and resetting on pull on refresh will solve the problem.
In below code, I am resetting the stream on button press. Hope that helps you.
import 'dart:async';
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return new _MyAppState();
}
}
class _MyAppState extends State<MyApp> {
var stream; // state variable
@override
void initState() {
super.initState();
stream = newStream(); // initial stream
}
Stream<String> newStream() =>
Stream.periodic(Duration(seconds: 1), (i) => "$i");
@override
Widget build(BuildContext context) {
var streamBuilder = StreamBuilder(
initialData: "0",
stream: stream,
builder: (context, snapshot) {
return new Text(snapshot.data);
});
return MaterialApp(
title: 'Trial',
home: Scaffold(
appBar: AppBar(title: Text('Stream builder')),
body: Column(
children: <Widget>[
streamBuilder,
FlatButton(
onPressed: () {
setState(() {
stream = newStream(); //refresh/reset the stream
});
},
child: Text("Reset"))
],
)));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With