简体   繁体   English

我如何从 Flutter 中的 Api 的嵌套对象中获取价值?

[英]how i can get value From Nested object From Api in Flutter?

i am working on a project and my problem is related to Nested Object in api.我正在做一个项目,我的问题与 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"}", .其实我想从这一行“数据”:“{“消息”:“Saim12345与你确认约会日期为15-06-2022下午06:20在线视频咨询”}”,。 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 "只有消息值如“ Saim12345 已与您确认约会日期为 15-06-2022 下午 06:20 在线视频咨询

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我已经尝试 JsonEcode 来获取它的索引,但效果不佳,我也创建了单独的数据类并创建了字符串消息,但是如果有人可以帮助我,请尽快回复我

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,
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                            
                                          ],
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            );
                          }))

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

Unfortunately your data is String you have to convert it to json and parse it so do this不幸的是,您的数据是字符串,您必须将其转换为 json 并解析它,所以这样做

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

then send this json to Data Model using......然后使用......将此json发送到数据模型

   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,
   };
   }

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这是我想要Saim12345 与您确认约会日期为 15-06-2022 下午 06:20 在线视频咨询的结果

  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);
      }

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

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