1

I try to get the documents from a collection and map to a model, so far so good. The problem is that when I add a document with invalid fields, the error occurs.

This is my model class ethis is my model class

My HomePage

class HomePage extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
 final _plantsProvider = Provider.of<PlantsProvider>(context);
 List<Plant> plants;
 return Scaffold(
  body: Container(
    child: SafeArea(
        child: StreamBuilder(
      stream: _plantsProvider.fetchPlantsStream(),
      builder: (_, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasData && snapshot.data!.docs.length > 0) {
          plants = snapshot.data!.docs.map(
            (doc) {
              return Plant.fromJSON(doc.data(), doc.id);
            },
          ).toList();
          return ListView.builder(
            itemCount: plants.length,
            itemBuilder: (buildContext, index) =>
                ListTile(title: Text(plants[index].name!)),
          );
        } else
          return CircularProgressIndicator();
      },
      )),
    ),
  );
 }
}

correct document

enter image description here

Bad document, error occurs only when I add document with wrong fields. In this case other. Any way to control that?

enter image description here

Error enter image description here

EdwinU
  • 85
  • 1
  • 12

1 Answers1

4

This line of code is causing the error:

plants[index].name!

The null assertion operator (!) tells the linter that the value of name can never be null. This allows you to use plants[index].name as a String. Since the name can sometimes be null, it would be better to use the ? operator, indicating that the value is of type String?

One way to resolve this is to tell the linter that the value can be null and to use a null check that provides an alternate value:

plants[index]?.name ?? 'Name'
CoderUni
  • 5,474
  • 7
  • 26
  • 58