Home > Back-end >  How to solve "The property 'length' can't be unconditionally accessed because th
How to solve "The property 'length' can't be unconditionally accessed because th

Time:04-02

import 'package:bloc_sample/blocs/product_bloc.dart';
import 'package:flutter/material.dart';

import '../blocs/cart_bloc.dart';
import '../models/cart.dart';

class ProductListScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("eCommerce"),
        actions: [
          IconButton(
            icon: Icon(Icons.shopping_cart),
            onPressed: () => Navigator.pushNamed(context, "/cart"),
          )
        ],
      ),
      body: buildProductList(),
    );
  }

  buildProductList() {
    return StreamBuilder(
      initialData: productBloc.getAll(),
      stream: productBloc.getStream,
      builder: (context, snapshot) {
        return snapshot.data.length > 0 //ERROR
            ? buildProductListItems(snapshot)
            : Center(
                child: Text("No data"),
              );
      },
    );
  }

  buildProductListItems(AsyncSnapshot snapshot) {
    return ListView.builder(
        itemCount: snapshot.data.length,
        itemBuilder: (BuildContext context, index) {
          final list = snapshot.data;
          return ListTile(
            title: Text(list[index].name),
            subtitle: Text(list[index].price.toString()),
            trailing: IconButton(
              icon: Icon(Icons.add_shopping_cart),
              onPressed: () {
                cartBloc.addToCart(Cart(list[index], 1));
              },
            ),
          );
        });
  }
}

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

I tried "?" or "!" but its doesn't work. Can You help me? How can I solve this problem?

CodePudding user response:

The compiler isn't sure that snapshot.data isn't null. It also doesn't know that its a List. (I assume its a List since you're accessing the length property).

So here you need a combo of the bang operator ! and a type cast.

If it's a Map just change the typecast to Map.

(snapshot.data! as List).length > 0

The other option is a null check.

if (snapshot.data != null) {
    return buildProductListItems(snapshot);
 } else {
    return Center(child: Text("No data"),
 );
}

Which one to choose depends on your implementation of product.getStream. If it's always at least an empty list and never null, then use the first option. If it's actually null if there's no data, then use the null check.

  • Related