product_list_screen.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<Object?> snapshot) {
return ListView.builder(
itemCount: snapshot.data.length, //error
itemBuilder: (BuildContext context, index) {
var list = snapshot.data;
return ListTile(
title: Text(list[index].name), //error
subtitle: Text(list[index].price.toString()), //error
trailing: IconButton(
icon: Icon(Icons.add_shopping_cart),
onPressed: () {
cartBloc.addToCart(Cart(List[index], 1)); //error
},
),
);
});
}
}
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 used '!' or '?' but its didn't work. Can you help me? Thanks.
CodePudding user response:
You can try using null
aware operator :
snapshot.data?.length ?? 0
CodePudding user response:
Do not use StreamBuilder use FutureBuilder Example:
FutureBuilder<Object?>(
future: _fetchNetworkCall, // async work
builder: (BuildContext context, AsyncSnapshot<Object?>snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting: return Text('Loading....');
default:
if (snapshot.hasError)
return Text('Error: ${snapshot.error}');
else
return Text('Result: ${snapshot.data}');
}
},
)