Home > Mobile >  how i can get value From Nested object From Api in Flutter?
how i can get value From Nested object From Api in Flutter?

Time:06-21

i am working on a project and my problem is related to Nested Object in api. I want to get message from my data object and it is not accessible and my model class don't give no thing about message. Actually I want from this line "data":"{"message":"Saim12345 Has a Confirmed Appointment with you Dated 15-06-2022 at 06:20 PM at Online Video Consultation"}", . Only the message value such as "Saim12345 Has a Confirmed Appointment with you Dated 15-06-2022 at 06:20 PM at Online Video Consultation"

I have tried JsonEcode to get its Index but not working well and i am also Created Seperate class of Data and created String message but that accesseed but gives null error if anybody can help me please response me as soon as possible

For Further This is my Model Class

List<NotificationModel> notificationModelFromJson(String str) => List<NotificationModel>.from(json.decode(str).map((x) => NotificationModel.fromJson(x)));

String notificationModelToJson(List<NotificationModel> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class NotificationModel {
  NotificationModel({
    this.id,
    this.type,
    this.notifiableType,
    this.notifiableId,
    this.data,
    this.readAt,
    this.createdAt,
    this.updatedAt,
  });

  double id;
  String type;
  String notifiableType;
  int notifiableId;
  String data;
  DateTime readAt;
  DateTime createdAt;
  DateTime updatedAt;

  factory NotificationModel.fromJson(Map<String, dynamic> json) => NotificationModel(
    id: json["id"].toDouble(),
    type: json["type"],
    notifiableType: json["notifiable_type"],
    notifiableId: json["notifiable_id"],
    data: json["data"],
    readAt: DateTime.parse(json["read_at"]),
    createdAt: DateTime.parse(json["created_at"]),
    updatedAt: DateTime.parse(json["updated_at"]),
  );

  Map<String, dynamic> toJson() => {
    "id": id,
    "type": type,
    "notifiable_type": notifiableType,
    "notifiable_id": notifiableId,
    "data": data,
    "read_at": readAt.toIso8601String(),
    "created_at": createdAt.toString(),
    "updated_at": updatedAt.toString(),
  };
}

This my Class



class PatientNotification extends StatefulWidget {
  final int notificationModelId;
  const PatientNotification({Key key, this.notificationModelId}) : super(key: key);


  @override
  State<PatientNotification> createState() => _PatientNotificationState();
}

class _PatientNotificationState extends State<PatientNotification> {
  NotificationModel notification;

  List<NotificationModel> notificationModelList = [];
  bool loading = true;
  Map mapResponse;


  

  void getNotifications() async {
    notificationModelList = [];
    Network network = new Network();
    var response = await network.getData("/notifications");


    log(response.body);


   

    if (response.statusCode == 200) {
      var json = cnv.jsonDecode(response.body);


      // try{
      if (json != null) {
        json.forEach((element) {
          notificationModelList.add(new NotificationModel.fromJson(element));
        });
        print(notificationModelList.length);
      }
      //   }catch(e){
      //     // log(e);
      // }

    }
    setState(() {
      notificationModelList = notificationModelList;
      // datalist=datalist;

      loading = false;
    });
  }


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


  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  GestureDetector(
                    onTap: () {
                      Navigator.pop(context);
                    },
                    child: Icon(
                      Icons.arrow_back_rounded,
                      color: AppColor.primary,
                      //size: .0,
                      // semanticLabel: 'Text to announce in accessibility modes',
                    ),
                  ),
                  TextButton(
                    onPressed: getNotifications,
                    child: Text(
                      "Notifications",
                      textAlign: TextAlign.left,
                      style: TextStyle(
                          fontSize: 24,
                          letterSpacing: 0.7,
                          color: Colors.black),
                    ),
                  ),
                ],
              ),
              SizedBox(
                height: 10,
              ),
              Expanded(child: SingleChildScrollView(
                  child: Container(
                      height: MediaQuery
                          .of(context)
                          .size
                          .height * 0.8,
                      child: loading ? AppWidgetsCard.getProgressIndicator()
                          : notificationModelList.isEmpty
                          ? AppWidgetsCard.getEmptyCard('Notification') :
                      ListView.builder(
                          itemCount: notificationModelList.length,
                          itemBuilder: (context, index) {
                            NotificationModel data = notificationModelList[index];

                            String dateFormate = DateFormat()
                                .add_yMMMEd()
                                .format(DateTime.parse(
                                data.createdAt.toString()));
                            String time = DateFormat()
                                .add_jm()
                                .format(DateTime.parse(
                                data.createdAt.toString()));
                            return Container(
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(15),
                              ),
                              height: 110,
                              width: MediaQuery
                                  .of(context)
                                  .size
                                  .width,
                              padding: EdgeInsets.symmetric(
                                  horizontal: 1, vertical: 5),
                              child: Card(
                                elevation: 5,
                                shape: RoundedRectangleBorder(
                                  borderRadius:
                                  BorderRadius.circular(15.0),
                                ),
                                child: Row(
                                  children: [
                                    Container(
                                      height: 100,
                                      width: 100,
                                      decoration: BoxDecoration(
                                          borderRadius:
                                          BorderRadius.only(
                                            bottomLeft:
                                            Radius.circular(15),
                                            topLeft:
                                            Radius.circular(15),
                                            // topRight:
                                            //     Radius.circular(15),
                                            // bottomRight:
                                            //     Radius.circular(15),
                                          ),
                             
                                          image: DecorationImage(
                                              image: NetworkImage(
                                                  'https://emedz.net/images/doctors/male-avi.jpg'),
                                              fit: BoxFit.fill
                                          )

                                      ),

                                    ),
                                    Expanded(
                                      child: Padding(
                                        padding:
                                        const EdgeInsets.all(8.0),
                                        child: Row(
                                          mainAxisAlignment:
                                          MainAxisAlignment
                                              .spaceBetween,
                                          children: [
                                            Expanded(
                                              child: Column(
                                                mainAxisAlignment:
                                                MainAxisAlignment
                                                    .spaceBetween,
                                                crossAxisAlignment:
                                                CrossAxisAlignment
                                                    .start,
                                                children: [
                                                  Text(
                                                    data.data,
                                                    style: TextStyle(
                                                        fontSize: 12,
                                                        color: Colors
                                                            .black,
                                                        fontWeight:
                                                        FontWeight
                                                            .bold),
                                                  ),
                                                  Expanded(
                                                      child:
                                                      SizedBox()),
                                                  Text('',
                                                    style: TextStyle(
                                                        fontSize: 10,
                                                        color: Colors
                                                            .blue),
                                                  ),
                                                  
                                                  Text(
                                                    '$dateFormate at $time  ',
                                                    maxLines: 2,
                                                    style: TextStyle(
                                                      fontSize: 14,
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                            
                                          ],
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            );
                          }))

              ),
              )
            ],
          ),
        ));
  }
}

CodePudding user response:

Unfortunately your data is String you have to convert it to json and parse it so do this

        dataJson = data.substring(1, data.length-1); //it will remove double quotes from string

then send this json to Data Model using......

   final dataModel = dataModelFromJson(dataJson);// this line where you pass dataJson

Below is your Data Model Class.......

   DataModel dataModelFromJson(String str) => 
   DataModel.fromJson(json.decode(str));

   String dataModelToJson(DataModel data) => json.encode(data.toJson());

   class DataModel {
   DataModel({
    @required this.message,
   });

   String message;

   factory DataModel.fromJson(Map<String, dynamic> json) => DataModel(
      message: json["message"],
   );

   Map<String, dynamic> toJson() => {
    "message": message,
   };
   }

CodePudding user response:

I have resolved it in way such as

and printed my message

This is the result that i want Saim12345 Has a Confirmed Appointment with you Dated 15-06-2022 at 06:20 PM at Online Video Consultation

  if (json != null) {
        json.forEach((element) {

          Map obj= element;
           message=obj['data'];
          message = message.replaceRange(0, 12, '');
          message = message.replaceRange((message.length-2), message.length, '');
       print(message);
          // var klk= cnv.jsonDecode(plm);
          print(message.toString());
          notificationModelList.add(new NotificationModel.fromJson(element));
        });
        print(notificationModelList.length);
      }
  • Related