简体   繁体   English

如何从 flutter 中的 api 响应中获取数组中的 object

[英]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.我正在尝试使用 class model 集成 api。这是我的 api 响应。

{
    "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这是我的 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这是我如何在我的 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现在,问题是我想访问这个 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.使用相同的 model。我的 model 只访问不在 object 中的数据,我想在我的模式下创建一个列表变量或其他东西,它可以访问 object 形式的数据。

here is the code how i'm calling api function on ui screen这是我在用户界面屏幕上调用 api function 的代码

 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请试试这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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