Toujo
Toujo

Reputation: 345

How to display JSON data?

How to display DietName which is under Data? I can display the item which is under PartnerData[] But what is the syntax just to display DietName?

{
    "Status": "1",
    "Message": "",
    "Data": {
        "EncDietId": "pEl2B9kuumKRxIxLJO76eQ==",
        "DietName": "dietcian2",
        "Email": null,
        "Phone": null,
        "AlternatePhone": null,
        "Image": "http://mjjjjctor/65AUEYMCUE8RTD2UKBRV.jpg",
        "Description": null,
        "Fee": null,
        "DiscountedFee": null,
        "BookingFee": null,
        "VisitDay": null,
        "TimeFrom": null,
        "TimeTo": null
    },
    "PartnerData": [
        {
            "PartnerId": "13",
            "EncPartnerId": "65gtodyhbtdInTsJWr1ZkA==",
            "PartnerName": "Rasomoy pvt. Hospital",
            "PartnerAddress": "Kol,Kol,Kol,Wb",
            "Fee": "1200",
            "DiscountedFee": "900",
            "BookingFee": "500",
            "DayList": [
                {
                    "DayName": "Wednesday",
                    "TimeFrom": "10:00",
                    "TimeTo": "16:00"
                },
                {
                    "DayName": "Friday",
                    "TimeFrom": "10:00",
                    "TimeTo": "16:00"
                },
                {
                    "DayName": "Saturday",
                    "TimeFrom": "10:00",
                    "TimeTo": "16:00"
                }
            ]
        }
    ]
}

Model class:

  DietDetailsModel dietDetailsModelFromJson(String str) => DietDetailsModel.fromJson(json.decode(str));

String dietDetailsModelToJson(DietDetailsModel data) => json.encode(data.toJson());

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

    String status;
    String message;
    Data data;
    List<PartnerDatum> partnerData;

    factory DietDetailsModel.fromJson(Map<String, dynamic> json) => DietDetailsModel(
        status: json["Status"],
        message: json["Message"],
        data: Data.fromJson(json["Data"]),
        partnerData: List<PartnerDatum>.from(json["PartnerData"].map((x) => PartnerDatum.fromJson(x))),
    );

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

class Data {
    Data({
        required this.encDietId,
        required this.dietName,
        required this.email,
        required this.phone,
        required this.alternatePhone,
        required this.image,
        required this.description,
        required this.fee,
        required this.discountedFee,
        required this.bookingFee,
        required this.visitDay,
        required this.timeFrom,
        required this.timeTo,
    });

    String encDietId;
    String dietName;
    dynamic email;
    dynamic phone;
    dynamic alternatePhone;
    String image;
    dynamic description;
    dynamic fee;
    dynamic discountedFee;
    dynamic bookingFee;
    dynamic visitDay;
    dynamic timeFrom;
    dynamic timeTo;

    factory Data.fromJson(Map<String, dynamic> json) => Data(
        encDietId: json["EncDietId"],
        dietName: json["DietName"],
        email: json["Email"],
        phone: json["Phone"],
        alternatePhone: json["AlternatePhone"],
        image: json["Image"],
        description: json["Description"],
        fee: json["Fee"],
        discountedFee: json["DiscountedFee"],
        bookingFee: json["BookingFee"],
        visitDay: json["VisitDay"],
        timeFrom: json["TimeFrom"],
        timeTo: json["TimeTo"],
    );

    Map<String, dynamic> toJson() => {
        "EncDietId": encDietId,
        "DietName": dietName,
        "Email": email,
        "Phone": phone,
        "AlternatePhone": alternatePhone,
        "Image": image,
        "Description": description,
        "Fee": fee,
        "DiscountedFee": discountedFee,
        "BookingFee": bookingFee,
        "VisitDay": visitDay,
        "TimeFrom": timeFrom,
        "TimeTo": timeTo,
    };
}

My API

Future<List<PartnerDatum>> dietcianDetailsApi() async {
var jsonResponse;

  var response = await http.post(
      Uri.parse("http://mjjjjapi/DietDetails"),
      body: ({
        'EncId': encDietcianIdRef,
      }));
  if (response.statusCode == 200) {
    print("Correct");
    print(response.body);
    jsonResponse = json.decode(response.body.toString());
    print(jsonResponse);
     //Navigator.push(context, MaterialPageRoute(builder: (context)=>AfterSearchPage(rresponse: SearchApiResponse.fromJson(jsonResponse))));
      DietDetailsModel dataModel = dietDetailsModelFromJson(response.body);
    print(dataModel.partnerData.length);
    for (final item in dataModel.partnerData) 
    print(item.partnerName);

    List<PartnerDatum> arrData =dataModel.partnerData;
   // print(arrData[1].partnerName);
    return arrData;

  } else {
    print("Wrong Url");
    print(response.body);
    throw Exception("Faild to fetch");
  }
  //return AllDietician();

}

Printing My PartnerData items . But How to display DietName which is inside Data?

class DietcianDetailsPage extends StatefulWidget {
  var encDietcianId;
  DietcianDetailsPage(this.encDietcianId);

  @override
  _DietcianDetailsPageState createState() => _DietcianDetailsPageState(this.encDietcianId);
}

class _DietcianDetailsPageState extends State<DietcianDetailsPage> {
  var encDietcianIdRef;// Need to pass is encId as a parameter in dietcianDetails Api
  _DietcianDetailsPageState(this.encDietcianIdRef);

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


  @override
  Widget build(BuildContext context) {
        var screenWidth = MediaQuery.of(context).size.width;
    var screenHeight = MediaQuery.of(context).size.height;
    var blockSizeHorizontal = (screenWidth/100);
    var blockSizeVertical= (screenHeight/100);
    return Scaffold(
       appBar: AppBar(
        elevation: 0.0,
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.topRight,
              colors: [
                Theme.of(context).primaryColor,
                Theme.of(context).accentColor
              ],
            ),
          ),
        ),
        title: Center(
          child: Image.asset(
      "assets/images/medbo.png",
      fit: BoxFit.contain,
      height: 52,),
        ),
        //toolbarHeight: 88,
    actions: [
      IconButton(onPressed: () => {}, icon: Icon(Icons.more_vert,size: 0.1,),),
    ],
      ),


      body: Container(
        child: Column(
          children: [
            Text(
             
             ""
            ),


            //========================================================================


             Container(
                      height: blockSizeVertical*30,//38
                      //color: Colors.blueAccent,
                      child: FutureBuilder(
                        future: dietcianDetailsApi(),

                        builder: (BuildContext context, AsyncSnapshot snapshot) {
                          // if (snapshot.connectionState !=ConnectionState.done) {
                          //   return CircularProgressIndicator();
                          // }
                          if (snapshot.hasError) {
                            return Text("Somthing went wrong");
                          }

                          if (snapshot.hasData) {
                            return ListView.builder(
                                 scrollDirection: Axis.horizontal,
                                  physics: BouncingScrollPhysics(),
                                shrinkWrap: true,
                                itemCount: snapshot.data.length,
                                itemBuilder: (BuildContext context, int index) =>
                                  Container(
                                    decoration: BoxDecoration(
                                    color: Colors.white,
                                    borderRadius: BorderRadius.circular(10),
                                  ),
                                  width: blockSizeHorizontal*80,
                                  margin: EdgeInsets.all(10),




                                  child: Stack(children: [
                        Column(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [


                               Padding(//====================images 
                              padding: const EdgeInsets.all(5.0),
                              
                            ),
  
                            SizedBox(height: blockSizeVertical*0.5),


                              Text(
                                'PartnerName :  ${snapshot.data[index].partnerName}',
                                style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: blockSizeHorizontal*3.5,
                                  fontFamily: 'Poppins',
                                  color: Theme.of(context).primaryColor,
                                ),
                                textAlign: TextAlign.center,
                              ),

Upvotes: 1

Views: 534

Answers (2)

Felipe Vergara
Felipe Vergara

Reputation: 869

The problem is dietcianDetailsApi because you return a List< PartnerDatum> and this model doesn't contains a DietName.

First solution is modify your function (dietcianDetailsApi), needs modify the data type that this function return, because the DietDetailsModel model contains both variables that you need.

Example:

Inside of dietcianDetailsApi you can assign the value, like this:

Future<DietDetailsModel> dietcianDetailsApi() async {
var jsonResponse;

  var response = await http.post(
      Uri.parse("http://medbo.digitalicon.in/api/medboapi/DietDetails"),
      body: ({
        'EncId': encDietcianIdRef,
      }));

  if (response.statusCode == 200) {
    jsonResponse = json.decode(response.body.toString());
    DietDetailsModel dataModel = dietDetailsModelFromJson(response.body);
    
    return dataModel
  } else {
    print("Wrong Url");
    print(response.body);
    throw Exception("Faild to fetch");
  }

Finally, you can replace your FutureBuilder for this:

FutureBuilder(
    future: dietcianDetailsApi(),
    builder: (BuildContext context, AsyncSnapshot snapshot) {
      if (snapshot.hasError) {
        return Text("Somthing went wrong");
      }

      if (snapshot.hasData) {
        var dietDetails = snapshot.data;
        print('PartnerData: ${dietDetails.partnerData}');
        print('DietName: ${dietDetails.data.dietName}');

        // ADD YOUR CODE
      } 
     }
    ),

Upvotes: 1

Christian
Christian

Reputation: 4641

Your Future is returning only the partnerData while it could as well return the whole DietDetailsModel in one object.

If you return the DietDetailsModel dataModel you could then consume the response in DietcianDetailsPage. Your ListView would use dataModel.data.partnerData but you could also access dataModel.data.data.

I hope I did not mix up the fields in your code.

Upvotes: 1

Related Questions