Search code examples
flutterdartstream-builder

how to create instances of StreamBuilder<UserModel>


I have this part in my code that I want to repeat throughout the project and I wish to just be able to call this function elsewhere, but the problem is that you need to pass snapshot.data to the widget down the tree,, any ideas how to do that ?

Widget UserStreamBuilderShortcut(BuildContext context, Widget widget){

  final _user = Provider.of<UserModel>(context);

  return

    StreamBuilder<UserModel>(
      stream: UserProvider(userID: _user.userID).userData,
      builder: (context, snapshot){
        if(snapshot.hasData == false){
          return LoadingFullScreenLayer();
        } else {
          UserModel userModel = snapshot.data; // cant pass this to instances of UserStreamBuilderShortcut Widget
          return
            widget; // in instances of this UserStreamBuilderShortcut we need to be able to pass snapshot.data here
        }
      },
    );

}

Solution

  • You could specify a builder parameter for this

    // define a Function type that takes a BuildContext and UserModel
    // and returns a Widget
    typedef UserModelWidgetBuilder = Widget Function(
      BuildContext context,
      UserModel userModel,
    );
    
    // pass it as a parameter in the shortcut function
    Widget UserStreamBuilderShortcut({
      BuildContext context,
      UserModelWidgetBuilder builder,
    }) {
      final _user = Provider.of<UserModel>(context);
    
      return StreamBuilder<UserModel>(
        stream: UserProvider(userID: _user.userID).userData,
        builder: (context, snapshot) {
          if (snapshot.hasData == false) {
            return LoadingFullScreenLayer();
          } else {
            UserModel userModel = snapshot.data;
            return builder(context, userModel);
          }
        },
      );
    }
    

    Now you can call this as follows:

    UserStreamBuilderShortcut(
      context: context,
      builder: (context, UserModel userModel) {
        return Container(); // create widget with UserModel
      },
    ),