Rageh Azzazy
Rageh Azzazy

Reputation: 757

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
        }
      },
    );

}

Upvotes: 0

Views: 103

Answers (2)

Ayren King
Ayren King

Reputation: 427

If you use the Provider package you can call its stream arguments from its child widgets.

Parent Widget:

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return StreamProvider<BrewList>.value(
      value: Database().brewList,
      child: MaterialApp(
        home: BrewListTile(),
      ),
    );
  }
}

Child Widget that has access to the stream.

class _BrewListState extends State<BrewList> {
  @override
  Widget build(BuildContext context) {
    final brews = Provider.of<List<Brew>>(context) ?? [];
    return Text(brews[0].text);

Upvotes: 0

dumazy
dumazy

Reputation: 14445

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
  },
),

Upvotes: 1

Related Questions