![](/img/trans.png)
[英]How can I get a value from firebase and and put it in a text in Flutter
[英]how i can get value From Nested object From Api in Flutter?
我正在做一個項目,我的問題與 api 中的嵌套對象有關。 我想從我的數據對象中獲取消息,但它無法訪問,而且我的模型類沒有提供任何關於消息的信息。 其實我想從這一行“數據”:“{“消息”:“Saim12345與你確認約會日期為15-06-2022下午06:20在線視頻咨詢”}”,。 只有消息值如“ Saim12345 已與您確認約會日期為 15-06-2022 下午 06:20 在線視頻咨詢”
我已經嘗試 JsonEcode 來獲取它的索引,但效果不佳,我也創建了單獨的數據類並創建了字符串消息,但是如果有人可以幫助我,請盡快回復我
進一步這是我的模型類
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(),
};
}
這是我的課
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,
),
),
],
),
),
],
),
),
),
],
),
),
);
}))
),
)
],
),
));
}
}
不幸的是,您的數據是字符串,您必須將其轉換為 json 並解析它,所以這樣做
dataJson = data.substring(1, data.length-1); //it will remove double quotes from string
然后使用......將此json發送到數據模型
final dataModel = dataModelFromJson(dataJson);// this line where you pass dataJson
下面是您的數據模型類.......
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,
};
}
我已經解決了它,例如
並打印了我的信息
這是我想要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.