Gary Frewin
Gary Frewin

Reputation: 565

Flutter Widgets - access to parent stream

I have a Streambuilder in flutter on my homescreen like this:

Then I have a SilverListDelegate which has a list of widgets

class _HomeScreenState extends State<HomeScreen> {
  @override
  Widget build(BuildContext context) {
    final auth = AuthProvider.of(context).auth;
    return Scaffold(
        body: StreamBuilder<User>(
            stream: auth.user,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                User user = snapshot.data;
                return CustomScrollView(
                  slivers: <Widget>[
                    SliverList(
                      delegate: SliverChildListDelegate([
                        SizedBox(height: 40),
                        userImageWidget,
                        userNameWidget,
                        ....,

the widgets are defined inside the HomeScreenState class like this:

  Widget userNameWidget = Text('Show Username',
      textAlign: TextAlign.center,
      style: TextStyle(
        fontSize: 28,
        fontWeight: FontWeight.bold,
        color: Colors.white,
      ));

How do I get the username from the stream in this case?

I know that if I just put the Text code directly in the SliverList I could say: Text(user.firstName) but this doesn't work if I put it into the widget above as it throws 'undefined name: user'.

Thanks

Upvotes: 0

Views: 200

Answers (1)

Max Weber
Max Weber

Reputation: 1088

You have to extract an own widget for the Text Widget. Then you can pass the value down to it.

class UserTextWidget extends StatelessWidget {
  final String username;

  const UserTextWidget({Key key, this.username}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Text('Show $username',
        textAlign: TextAlign.center,
        style: TextStyle(
          fontSize: 28,
          fontWeight: FontWeight.bold,
          color: Colors.white,
        ));
  }
}

Alternatively you could create a method that returns the text widget instead of a variable.

  Widget userNameWidget(String username){
    return Text('Show $username',
      textAlign: TextAlign.center,
      style: TextStyle(
        fontSize: 28,
        fontWeight: FontWeight.bold,
        color: Colors.white,
      ));

https://codepen.io/md-weber/pen/LYpWWdr

Upvotes: 1

Related Questions