简体   繁体   中英

How to get the object from array from api response in flutter

I'm trying to integrate the api using class model. here is my api response look like.

{
    "status": 1,
    "message": "your rides",
    "data": [
        {
            "id": 2,
            "ride_user_id": "4",
            "ride_driver_id": "2",
            "pick_up": "gsdhjhsgdf",
            "drop_of": "dsfbsdjbf",
            "date": null,
            "time": "10.55",
            "status": "complete",
            "created_at": "2022-06-17T09:50:25.000000Z",
            "updated_at": "2022-06-17T09:56:37.000000Z",
            "driver": {
                "id": 2,
                "name": "driver",
                "vehicle_number": null,
                "licence_number": null,
                "state": null,
                "image": null,
                "notification": 1,
                "created_at": "2022-06-08T16:15:12.000000Z",
                "updated_at": "2022-06-08T16:15:44.000000Z"
            },
            "rideperson": {
                "id": 4,
                "name": "ab",
                "vehicle_number": null,
                "licence_number": null,
                "state": "ascascas",
                "image": "profile/1735772987889499.jfif",
                "notification": 1,
                "created_at": "2022-06-09T07:54:41.000000Z",
                "updated_at": "2022-06-16T06:48:37.000000Z"
            },
            "rating": {
                "id": 2,
                "sender_id": null,
                "reciever_id": null,
                "ride_id": 2,
                "rating": "4",
                "created_at": "2022-06-17T09:59:38.000000Z",
                "updated_at": "2022-06-17T09:59:38.000000Z"
            }
        }
    ]
}

and here is my model

import 'dart:convert';

import 'package:flutter/foundation.dart';


MyRides rideFromJson(String str) => MyRides.fromJson(json.decode(str));

String rideToJson(MyRides data) => json.encode(data.toJson());
class MyRidesDetails {
  final int id;
  final String pickUp;
  final String dropOff;
  final String time;
  final String rideUserId;
  final String rideDriverId;
  final List driver;

  MyRidesDetails(
      {required this.id,
      required this.pickUp,
      required this.dropOff,
      required this.time,
      required this.rideUserId,
      required this.rideDriverId,
      required this.driver
      
      });

  factory MyRidesDetails.fromJson(Map<String, dynamic> json) => MyRidesDetails(
        id: json['id'],
        dropOff: json['drop_of'],
        pickUp: json['pick_up'],
        time: json['time'],
        rideUserId: json['ride_user_id'],
        rideDriverId: json['ride_driver_id'],
        driver: json['data']['driver']

      );
  Map<String, dynamic> toJson() => {
        'id': id,
        'drop_of': dropOff,
        'pick_up': pickUp,
        'time':time,
        'rating':time,
        'ride_user_id':rideUserId,
        'ride_driver_id':rideDriverId,
        'driver':driver
        
      };
}




class MyRides {
    MyRides({
        required this.status,
        required this.message,
        required this.data,
       
    });

    int status;
    String message;
    List<MyRidesDetails> data;

    

    factory MyRides.fromJson(Map<String, dynamic> json) => MyRides(
        status: json["status"],
        message: json["message"],
        data: List<MyRidesDetails>.from(json["data"].map((x) => MyRidesDetails.fromJson(x))),
       
    );

    Map<String, dynamic> toJson() => {
        "status": status,
        "message": message,
        "data": List<dynamic>.from(data.map((x) => x.toJson())),
       
    };
}

here is the code how i'm populating data on my model

 Future getAllMyRides(role) async {
    Map<String, String> headers = {
      "Content-type": "application/json",
      'Authorization': 'Bearer $token',
    };
    var url = Uri.parse(ApiPath.getAllMyRidesUrl+role);
    final response = await http.get(url, headers: headers);
    if (response.statusCode == 200) {
      return rideFromJson(response.body).data;
    } else {
      throw Exception('Failed to load post');
    }
  }

Now, the question is i want to access this object

"driver": {
      "id": 2,
      "name": "driver",
      "vehicle_number": null,
      "licence_number": null,
      "state": null,
      "image": null,
      "notification": 1,
      "created_at": "2022-06-08T16:15:12.000000Z",
      "updated_at": "2022-06-08T16:15:44.000000Z"
 },

using the same model. My model is only accessing the data which is not in object, i want to create a list variable or something on my mode which can access those data which is in object form.

here is the code how i'm calling api function on ui screen

 getAllMyRides() async {
    setState(() {
      _isLoading = true;
    });
    await Future.delayed(const Duration(seconds: 2), () async {
      connectionMsg = await services.checkInternetConnectivity();
    
      if (connectionMsg == "connected") {
        try {
          var _myRides = await services.getAllMyRides(role);

          if (myRides is MyRides) {
            print(_myRides.data[0].driver.id); //this should print 2
          } else {
            print("Unable to fetch data");
          }
         
          setState(() {
            _isLoading = false;
          });
        } catch (e) {
          print(e);
          setState(() {
            apiCrashed = true;
          });
        }
        setState(() {
          _isLoading = false;
        });
      } else if (connectionMsg == "not connected") {
        AppDialogs().showInfoDialogue(context, "Internet is not working!", () {
          Navigator.pop(context);
        });
        setState(() {
          _isLoading = false;
        });
      }
    });
  }


@override
  void initState() {
    super.initState();
    getAllMyRides();
  }

please help how to do this.Thanks.

var _myRides = await getAllMyRides();

var jsonDecoded = json.decode(_myRides);
print(jsonDecoded['data'][0]['driver']['id']);

please try this

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