Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refresh or reload a flutter firestore streambuilder manually?

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.

like image 691
Monkey D Naruto Avatar asked Sep 01 '18 23:09

Monkey D Naruto


People also ask

How do I refresh StreamBuilder in flutter?

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 .

How do I use StreamBuilder in flutter?

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 .

How do I use pull to refresh in flutter?

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.


Video Answer


1 Answers

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"))
              ],
            )));
  }
}
like image 130
Dinesh Balasubramanian Avatar answered Oct 15 '22 17:10

Dinesh Balasubramanian