enter image description here这是控制器类:我在使用getvehicle时遇到了同样的问题,所以我使用了as documentSnapshot来解决它
class TripsController {
FirebaseFirestore _firestore = FirebaseFirestore.instance;
Stream<List<Trips>> getTrips() {
return _firestore
.collection('trips')
.snapshots()
.map((snapshot) => snapshot.docs
.map((doc) => Trips(
id: doc.id,
departure: doc.data()?['departure'],
destination: doc.data()?['destination'],
vehicleID: doc.data()?['vehicleID'],
))
.toList());
}
Future<Vehicle> getVehicle(String id) async {
DocumentSnapshot snapshot = await _firestore.collection('vehicle').doc(id).get();
return Vehicle(
id: snapshot.id,
Driver: (snapshot.data as DocumentSnapshot)?['Driver'],
name: (snapshot.data as DocumentSnapshot)?['name'],
type: (snapshot.data as DocumentSnapshot)?['type'],
);
}
}
and this is the model
class Trips {
final String id ;
final String departure;
final String destination;
final String vehicleID;
Trips({required this.id,required this.departure, required this.destination, required this.vehicleID});
}
class Vehicle {
final String id ;
final String Driver;
final String name;
final String type;
Vehicle({required this.id ,required this.Driver, required this.name, required this.type});
}
我到处都有零安全的问题
2条答案
按热度按时间5vf7fwbs1#
Text
小部件不接受空值。在您的情况下,trips
列表是可空的,这就是为什么它显示错误,而Listview已经处理渲染项目。您可以像Text(trips![index].departure)
一样使用!
。其他人也是如此。但我更喜欢检查null或只是在ui上打印1cklez4t2#
通过删除
List<Trips>
后面的“?”,使其不可为空。在使用snapshot.hasData
进行初始化之前,您将检查它是否为空。如果快照没有数据,它将返回false,因此您将不会初始化List<Trips>
。你应该对
Vehicle
做同样的事情,你也检查那里的空性。您可以在此处查看snapshot.hasData的文档:https://api.flutter.dev/flutter/widgets/AsyncSnapshot/hasData.html