flutter 无法无条件调用方法“[]”,因为接收方可以为“null”,安全null的问题

vu8f3i0k  于 2023-03-31  发布在  Flutter
关注(0)|答案(2)|浏览(160)

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});
}

我到处都有零安全的问题

5vf7fwbs

5vf7fwbs1#

Text小部件不接受空值。在您的情况下,trips列表是可空的,这就是为什么它显示错误,而Listview已经处理渲染项目。您可以像Text(trips![index].departure)一样使用!。其他人也是如此。但我更喜欢检查null或只是在ui上打印

Text("${trips?[index].departure}")
1cklez4t

1cklez4t2#

通过删除List<Trips>后面的“?”,使其不可为空。在使用snapshot.hasData进行初始化之前,您将检查它是否为空。如果快照没有数据,它将返回false,因此您将不会初始化List<Trips>
你应该对Vehicle做同样的事情,你也检查那里的空性。
您可以在此处查看snapshot.hasData的文档:https://api.flutter.dev/flutter/widgets/AsyncSnapshot/hasData.html

相关问题