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 ?



Read more here: https://stackoverflow.com/questions/66342225/how-to-use-streambuilder-to-perform-network-requests-with-different-values

Content Attribution

This content was originally published by Calvin Gonsalves at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: