How to reload or refresh a Flutter StreamBuilder

In my last flutter code example, we explored how to create flutter StreamBuilder, how and when to use it.

To understand when to reload flutter StreamBuilder, consider situation when you need to reload the data stream source associated with StreamBuilder.

It might be when your app switches to another data stream or there is a new available data stream.

The example code will illustrate how to reload or refresh a flutter StreamBuilder.

CREATE NEW FLUTTER PROJECT

In your Visual Studio Code, go to View menu > Command Palette.

In the open dialog, select Flutter. Enter the name of your Flutter project and hit enter key button.

Right click on the lib folder and create a new dart file inside the folder.

Feel free to use a name of our choice. For the purpose of this example I will name my dart file – refresh_streambuilder.dart.

Open the file and add the code below.

import 'dart:async';

import 'package:flutter/material.dart';

class RefreshStreamBuilder extends StatefulWidget {
  @override
  _RefreshStreamBuilderState createState() => _RefreshStreamBuilderState();
}

class _RefreshStreamBuilderState extends State<RefreshStreamBuilder> {
  Stream<int> myStream;

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

  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(title: Text("Refresh StreamBuilder")),
      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"),
            color: Colors.red,
            onPressed: () {
              setState(() {
                myStream = timedCounter(
                    Duration(seconds: 1), 10); //refresh the stream here
              });
            },
          )
        ],
      ),
    );
  }
}

OPEN MAIN.DART FILE

Open the default main.dart file located inside the lib folder.

We need to import refresh_streambuilder.dart at the top of the page.

Assign an instance of the RefreshStreamBuilder class to the MaterialApp home attribute.

Add the code below to the main.dart file.

import 'package:flutter/material.dart';
import 'refresh_streambuilder.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: RefreshStreamBuilder(),
    );
  }
}

RUN YOUR APP

You can use flutter command to run your app – $ flutter run

If everything goes well, you will see screen similar to the image below in your flutter device.

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment