flutterstreamrxdart

Can a StreamBuilder return List<Widget>


An AppBar in flutter takes List<Widget> as actions. For some reason, I can't find a way to feed this property based on a StreamBuilder.

I have a BehaviorSubject (can change to other types of stream) where I am adding Widgets and I want to show those widgets in the AppBar (as action buttons)

// ....

var appBar = new AppBar(
        title: "appTitle",
        actions: _getActionWidgets()   // <= Can be fed by SteamBuilder?
      )
/// ...


// ...
// BehaviorSubject<Widget> actionWidgets;
// ...

List<Widget> _getActionWidgets(){
  return StreamBuilder(
    ... // what can be done here so that this method would return List<Widget>
  );

}

Most of the examples out there are for "ListView" using the ListView.builder(...) which is not applicable in my case here.

The end goal is to feed the actions property of AppBar using StreamBuilder and struggling to find a way. I appreciate any help or directions and thanks for your time reading my question.


Solution

  • No. This is not a case. Actions in your case are usually buttons (FlatButton, IconButton etc). Your case can looks like something below:

    class Bloc {
      final _subject = BehaviourSubject<List<Widget>>();
      ...  
    }
    
    void initState() {
      super.initState();
      // Prepare actions depending on condition
      final actions = [
        FlatButton(child: Text('Action 1'), onPressed: () {}),
        FlatButton(child: Text('Action 2'), onPressed: () {}),
      ];
      bloc.setActions(actions); // indeed send actions to sink
    }
    
    Widget build(BuildContext context) {
      return StreamBuilder<List<Widget>>(
        stream: bloc.actionStream, // Function of `bloc` which returns Stream<List<Widget>> (indeed IconButton, FlatButton)
        builder: (context,snapshot) {
          return Scaffold(
            appBar: AppBar(
              actions: snapshot.hasData? snapshot.data : <Widget>[],
            ),
          );
        }
      );
    }