简体   繁体   中英

How to retrieve data from firebase realtime database

There seems to be some change with recent update of firebase database.My project worked fine with the version firebase_database: ^7.0.0 but with the newer release of firebase database I can't update my project code.

Here is the working version for v7

class _MainScreenState extends State<MainScreen> {
//
 DatabaseReference driversRef =
      FirebaseDatabase(databaseURL: firebaseUrl).reference().child("Drivers");

//
void searchNearestDriver() {
    print("xxx searchNearestDriver");
    if (availableDrivers.length == 0) {
      cancelRideRequest();
      clear();
      noDriverFound();
      return;
    }
    var driver = availableDrivers[0];
    driversRef
        .child(driver.key!)
        .child('car_details')
        .child("type")
        .once()
        .then((DataSnapshot snap) async { //error from here
      if (await snap.value != null) {
        String carType = snap.value.toString();
        if (carType == carRideType) {
          notifyDriver(driver);
          //print("NotifyDriver is running");
          //TODO This removes the driver from geofire aswell re code

          //availableDrivers.removeAt(0);
        } else {
          Fluttertoast.showToast(msg: carRideType + "Driver not available");
        }
      }
    });
  }

The same code on firebase_database: ^9.0.12 gives an error. The error I receive is on `(DataSnapShot snap) async ){...} and the error is

The argument type 'Future Function(DataSnapshot)' can't be assigned to the parameter type 'FutureOr

The once method returns a DatabaseEvent , not a DataSnapshot in the newer versions I guess, This is the update.

void searchNearestDriver() async {
    print("xxx searchNearestDriver");
    if (availableDrivers.length == 0) {
      cancelRideRequest();
      clear();
      noDriverFound();
      return;
    }
    var driver = availableDrivers[0];
    //driversRef.child(driver.key!).child('car_details').child("type");
    // .once();

    DatabaseEvent event = await driversRef
        .child(driver.key!)
        .child('car_details')
        .child("type")
        .once();

    //.then((DataSnapshot snap) async {
    if (event.snapshot.value != null) {
      String carType = event.snapshot.value.toString();
      if (carType == carRideType) {
        notifyDriver(driver);
       
        //availableDrivers.removeAt(0);
      } else {
        Fluttertoast.showToast(msg: carRideType + "Driver not available");
      }
    }
  } //);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM