Issue
this is the "The Net Ninja" code adapted to the more recently flutter version by me:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:coffee_for_all/models/coffee.dart';
import 'package:coffee_for_all/services/auth.dart';
import 'package:flutter/material.dart';
import 'package:coffee_for_all/services/database.dart';
import 'package:provider/provider.dart';
import 'coffee_list.dart';
class Home extends StatelessWidget {
final AuthService _auth = AuthService();
var initialData;
@override
Widget build(BuildContext context) {
return StreamProvider<List<Coffee>>.value(
value: DatabaseService().coffees,
initialData: initialData,
child: Scaffold(
backgroundColor: Colors.brown[50],
appBar: AppBar(
title: Text('Coffee for all'),
backgroundColor: Colors.brown[400],
elevation: 0.0,
actions: <Widget>[
TextButton.icon(
icon: Icon(Icons.person),
label: Text('logout'),
style: TextButton.styleFrom(
primary: Colors.black,
),
onPressed: () async {
await _auth.signOut();
},
)
],
),
body: CoffeeList(),
),
);
}
}
And when I try to run the program this happens:
═════════════════════════════════════════════════════════════
Reloaded 5 of 680 libraries in 937ms.
════════ Exception caught by widgets library ════════════════
type ‘Null’ is not a subtype of type ‘List’
The relevant error-causing widget was
Home
lib\screens\wrapper.dart:18
══════════════════════════════════════════════════════════════
And this is where and how I define the List:
class Coffee {
final String? name;
final String? sugars;
final int? strength;
Coffee({this.name, this.sugars, this.strength});
}
class CoffeeList extends StatefulWidget {
@override
_CoffeeListState createState() => _CoffeeListState();
}
class _CoffeeListState extends State<CoffeeList> {
@override
Widget build(BuildContext context) {
final coffees = Provider.of<List<Coffee>>(context);
return ListView.builder(
itemCount: coffees.length,
itemBuilder: (context, index) {
return CoffeeTile(coffee: coffees[index]);
},
);
}
}
// coffee list from snapshot
List<Coffee> _coffeeListFromSnapShop(QuerySnapshot snapshot) {
return snapshot.docs.map((doc) {
return Coffee(
name: doc.get('name') ?? '',
strength: doc.get('strength') ?? 0,
sugars: doc.get('sugars') ?? '0',
);
}).toList();
}
// get coffees stream
Stream<List<Coffee>> get coffees {
return coffeeCollection.snapshots().map(_coffeeListFromSnapShop);
}
Can anyone help me with this error? Thanks!
Solution
Try this solution. There is no null check with the itemCount attribute of ListView.builder().
@override
Widget build(BuildContext context) {
final coffees = Provider.of<List<Coffee>>(context);
return ListView.builder(
itemCount: coffees!=null?coffees.length:0,
itemBuilder: (context, index) {
return CoffeeTile(coffee: coffees[index]);
},
);
}
}
Answered By – Vishal_VE
Answer Checked By – Willingham (FlutterFixes Volunteer)