Using a List in Flutters null safety is confusing me

Issue

I’m trying to migrate an existing, small Flutter app to Flutter 2.12. The null safety thing is new and still confusing to me. For the most part I have been successful in resolving the errors from the migration, but I haven’t found a solution for this problem. Here we go:

I have a simple ProductListclass defined as so:

class ProductList {
  int count = 0;
  List<Product> rows = [];
}

No errors exist in the class. In my main.dart class I am using a ListView to view the list. In the method that creates the ListTile, both of the lines that refer to the productList.rows variable show an error. Here is the code:

eturn ListView.separated(
          separatorBuilder: (context, index) => Divider(
                color: Colors.black,
              ),
          shrinkWrap: true,
          padding: const EdgeInsets.all(2.0),
          itemCount: productList.***rows***.length,
          itemBuilder: (context, i) {
            return _buildRow(productList.***rows***[i]);
          });

The error message for those lines is:

The property ‘rows’ can’t be unconditionally accessed because the receiver can be ‘null’.
Try making the access conditional (using ‘?.’) or adding a null check to the target (‘!’).

I have peppered those lines with every combination of ‘?’ and ‘!’ over time, and still no luck. I’m sure I’m overlooking something simple, but I have no idea what that is. I’m new to null safety so Im still at the bottom of the learning curve and most of the official documentation I’ve found reminds me of reading the K&R (obscure reference for the old programmers in the crowd). Hat am I doing wrong?

Solution

change your productList declaration to late ProductList productList;

Answered By – Lakmal Fernando

Answer Checked By – Terry (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.