Search code examples
flutterdartproviderstream-builderflutter-streambuilder

Flutter stream: Stream builder returns Null value


I'm trying to get data from Firestore via a stream, but it's returning null.

This is the code of my model.

class UserData {
  String? uid;
  String? name;
  String? sugar;
  int? strength;

  UserData(
      {required this.uid,
      required this.name,
      required this.sugar,
      required this.strength});
}

This is my service with streams

//User data from snapshot
  UserData _userDataFromSnapShot(DocumentSnapshot snapshot) {
    return UserData(
        uid: uid,
        name: snapshot['name'],
        sugar: snapshot['sugar'],
        strength: snapshot['strength']);
  }

  //Get user Doc stream
  Stream<UserData> get userData {
    return brewCollection.doc(uid).snapshots().map(_userDataFromSnapShot);
  }
}

And here I'd like to use the data I got from Firestore with Stream Builder. And try to show the name property of data in text form field, but here I got null value, although final user = Provider.of<MyUser?>(context); it returns Uid which i checked in print statements But the error always says StreamBuilder causing the error

    class _FormSettingState extends State<FormSetting> {
  final _formKey = GlobalKey<FormState>();
  final List<String> sugars = ['0', '1', '2', '3', '4', '5'];

  String? _currentName;
  String? _currentSugar = "0";
  dynamic _currentStrength;

  @override
  Widget build(BuildContext context) {
    final user = Provider.of<MyUser?>(context);
    return StreamBuilder<UserData>(
        stream: DataBaseServices(uid: user?.Uid).userData,
        builder: (context, snapshot) {
           if (snapshot.hasData) {
          UserData? userdata = snapshot.data;

          return Form(
            key: _formKey,
            child: Column(
              children: <Widget>[
                Text(
                  'Update your Brew Settings',
                  style: TextStyle(fontSize: 18.0),
                ),
                SizedBox(height: 20),
                TextFormField(
                  initialValue: userdata?.name,
                  decoration:
                      textInputDecoration.copyWith(hintText: 'Enter Name'),
                  onChanged: (val) => setState(() => _currentName = val),
                  validator: (val) =>
                      val!.isEmpty ? 'Please Enter value' : null,
                ),} 


else {
               return Loading();
           }

Here is the Error message enter image description here


Solution

  • I think issue is in your service file - "name: name: snapshot['name'],," to data is not assigning

    UserData _userDataFromSnapShot(DocumentSnapshot snapshot) {
        return UserData(
            uid: uid,
            name: snapshot['name'],
            sugar: snapshot['sugar'],
            strength: snapshot['strength']);
      }