ckot
ckot

Reputation: 359

type null is not a subtype of type 'String' error

 body: StreamBuilder<List<User>>(
        stream: readUsers(),
        builder: (context, snapshot) {
          if (snapshot.hasError) {
            return Text('Error ${snapshot.error}');
          }
          if (snapshot.hasData) {
            final users = snapshot.data!;

            return ListView(
              children: users.map(buildUser).toList(),
            );
          } else {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
        },
      )),

The part where I am trying to pull data from firebase.

  Widget buildUser(User user) => ListTile(leading: Text('${user.bmi}'));

The buildUser widget I created.

  Stream<List<User>> readUsers() => FirebaseFirestore.instance
  .collection('users')
  .snapshots()
  .map((snapshot) =>
      snapshot.docs.map((doc) => User.fromJson(doc.data())).toList());

The readUser structure I created

I am able to print data to the database and one of these data is a double value named 'bmi'. When I continue the process, it stays in the snapshot.haserror loop and

type null is not a subtype of type 'String'

prints the error.

    class User {
  final double bmi;

  User(
      {
      required this.bmi});

  Map<String, dynamic> toJson() => {
        'bmi': bmi,
      };

  static User fromJson(Map<String, dynamic> json) => User(
      bmi: json['bmi']);
}

Upvotes: 0

Views: 60

Answers (1)

rszf
rszf

Reputation: 201

i am not 100% sure, but i had the same error, where the json did not have that specific field. Before you try to get the 'bmi' field of json, check if it exists:

json.containsKey("bmi") ? json['bmi'] : "missing field" 

Upvotes: 2

Related Questions