簡體   English   中英

如何從 flutter 中的 api 響應中獲取數組中的 object

[英]How to get the object from array from api response in flutter

我正在嘗試使用 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"
            }
        }
    ]
}

這是我的 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())),
       
    };
}

這是我如何在我的 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');
    }
  }

現在,問題是我想訪問這個 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"
 },

使用相同的 model。我的 model 只訪問不在 object 中的數據,我想在我的模式下創建一個列表變量或其他東西,它可以訪問 object 形式的數據。

這是我在用戶界面屏幕上調用 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();
  }

請幫助如何做到這一點。謝謝。

var _myRides = await getAllMyRides();

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

請試試這個

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM