skip to Main Content

enter image description here this the controller class :
i had the same problems with getvehicle so i used as documentSnapshot to resolve it

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

am having a problems with null safety everywhere

2

Answers


  1. Text widget doesnt accept null value. In your case trips list is nullable, that’s why it is showing the error, While the Listview already handling the render items. You can use ! like Text(trips![index].departure). same goes for others. But I prefer checking null or just printing on ui

    Text("${trips?[index].departure}")
    
    Login or Signup to reply.
  2. Make the List<Trips> not nullable, by removing the ‘?’ after it. You are checking if it’s null or not before the initialization with the snapshot.hasData. If the snapshot doesn’t have data, it will return false, so you will not initialize List<Trips>.

    You should do the same for the Vehicle, you check the nullability there too.

    You can see the documentation for snapshot.hasData here: https://api.flutter.dev/flutter/widgets/AsyncSnapshot/hasData.html

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search