Home > Mobile >  type 'String' is not a subtype of type 'int' of 'index' while reading
type 'String' is not a subtype of type 'int' of 'index' while reading

Time:04-25

I have two files main.dart and a class history.dart the main.dart takes a DataSnapShot from firebase and the history.dart will sort out the Map.

the main.dart

late DatabaseReference rideRequestRef =
    FirebaseDatabase.instance.ref().child("Ride Requests");
static void obtainTripRequestsHistoryData(context) async {
    var keys = Provider.of<AppData>(context, listen: false).tripHistoryKeys;

    for (String key in keys) {
      rideRequestRef.child(key);

      DatabaseEvent event = await rideRequestRef.once();

      if (event.snapshot.value != null) {
        DatabaseEvent event =
            await rideRequestRef.child(key).child('rider_name').once();

        String name = event.snapshot.value.toString();

        if (name == userCurrentInfo.name) {
          var history = History.fromSnapshot(event.snapshot);
          Provider.of<AppData>(context, listen: false)
              .updateTripHistoryData(history);
        }
        //});
      }
      //});
    }
  }

the History.dart

class History {
  String? paymentMethod;
  String? createdAt;
  String? status;
  int? fares;
  String? dropOff;
  String? pickup;

  History(
      {this.paymentMethod,
      this.createdAt,
      this.status,
      this.fares,
      this.dropOff,
      this.pickup});

  History.fromSnapshot(DataSnapshot dataSnapshot) {
    dynamic data = dataSnapshot.value;

    paymentMethod = data["payment_method"];
    createdAt = data["created_at"];
    status = data["status"];
    fares = data["fares"];
    dropOff = data["dropoff_address"];
    pickup = data["pickup_address"];
  }
}

I get an error on paymentMethod = data["payment_method"];and the rest.

the error

Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'

Next, I changed to

  History.fromSnapshot(DataSnapshot dataSnapshot) {
    //Map<dynamic, dynamic> data = dataSnapshot.value as Map<dynamic, dynamic>;

    final data = Map<String, dynamic>.from(
        (dataSnapshot).value as Map);

    paymentMethod = data["payment_method"];
    createdAt = data["created_at"];
    status = data["status"];
    fares = data["fares"];
    dropOff = data["dropoff_address"];
    pickup = data["pickup_address"];
  }
}

The error

type 'String' is not a subtype of type 'Map<dynamic, dynamic>' in type cast

I have checked this forum throughout but most are unanswered. The ones that supposedly worked don't work for me.

CodePudding user response:

You're defining event twice:

DatabaseEvent event = await rideRequestRef.once(); //            
  • Related