Search code examples
flutterdartstream-builderflutter-futurebuilder

How to use StreamBuilder to perform network requests with different values


I'm using a FutureBuilder widget to render the Text based on the value of the future counter and when I click the floating action button I call the future again with a different value. But I need to do a setState after I click the button in order to refresh the UI, this would be fine for few widgets on the screen but calling setState would rebuild the other widgets too.


class _MyHomePageState extends State<MyHomePage> {
  Future counter;

  @override
  void initState() {
    super.initState();
    counter = counterFuture(4);
  }

  //This would be a network request with a specific value
  Future<int> counterFuture(int i) async {
    return await Future.value(i);
  }

  _changeCounter(int i) {
    setState(() {
      counter = counterFuture(i);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            FutureBuilder<int>(
              future: counter,
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  return Text(snapshot.data.toString());
                }
                return Text('loading');
              },
            ),
             ...other widgets
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        //tap button to request with a different value
        onPressed: () => _changeCounter(9),
      ),
    );
  }
}

My question is how can I achieve this using Streams and StreamBuilder to render and update only the Text widget ?


Solution

  • You can do so easily with a StreamController. Check out the code snippet below:

    class _MyHomePageState extends State<MyHomePage> {
      int counter;
      StreamController controller = StreamController<int>();
    
      @override
      void initState() {
        initialize();
        super.initState();
      }
    
      initialize() async {
        counter = await counterFuture(4);
        controller.add(counter);
      }
    
      @override
      void dispose() {
        controller.close();
       super.dispose();
      }
    
      //This would be a network request with a specific value
      Future<int> counterFuture(int i) async {
        return await Future.value(i);
      }
    
      _changeCounter(int i) async {
        counter = await counterFuture(i);
        controller.add(counter);
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: Text('Demo'),
            ),
            body: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  StreamBuilder<int>(
                    stream: controller.stream,
                    builder: (context, snapshot) {
                      if (snapshot.hasData) {
                        return Text(snapshot.data.toString());
                      }
                      return Text('loading');
                    },
                  ),
                ],
              ),
            ),
            floatingActionButton: FloatingActionButton(
               //tap button to request with a different value
             onPressed: () => _changeCounter(9)),
          ),
        );
      }
    }