How To Reload Or Refresh Stream Builder Using Flutter App

admin_img Posted By Bajarangi soft , Posted On 30-10-2020

Want to refresh or reload a flutter firestore streambuilder manually? 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.

How To Reload Or Refresh Stream Builder Using Flutter App

Refresh Stream Builder
Complete Code For Refresh Stream Builder In Flutter
main.dart

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Transform',
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Stream<int> myStream;

  @override
  void initState() {
    super.initState();
    myStream = timedCounter(Duration(seconds: 1), 20);
  }

  Stream<int> timedCounter(Duration interval, [int maxCount]) async* {
    int i = 0;
    while (true) {
      await Future.delayed(interval);
      yield i++;
      if (i == maxCount) break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.pink[800],
          title: Text("Refresh Stream Builder"
          )),
      body: ListView(
        children: <Widget>[
          SizedBox(height: 50),
          Center(
            child: StreamBuilder<int>(
              stream: myStream,
              builder: (context, snapshot) {
                if (!snapshot.hasData) {
                  return Text("Loading");
                }
                return Text("${snapshot.data.toString()}",
                    style: TextStyle(fontSize: 20));
              },
            ),
          ),
          SizedBox(height: 20.0),
          RaisedButton(
            child: Text("REFRESH",style: TextStyle(color: Colors.white),),
            color: Colors.pink[800],
            onPressed: () {
              setState(() {
                myStream = timedCounter(
                    Duration(seconds: 1), 10); //refresh the stream here
              });
            },
          )
        ],
      ),
    );
  }
}

Related Post