我是 Flutter 新手,在 HTTP 回應上決議 JSON 時遇到問題。
我正在使用 Airtable 后端來存盤有關帖子的資訊。這些總是包含影像,有時還包含附件 - PDF。
我構建了 PODO,如下所示:
class Post {
String recordid;
String timecreated;
String title;
String content;
String imgurl;
List<Pdf>? pdf;
Post({
required this.recordid,
required this.timecreated,
required this.title,
required this.content,
required this.imgurl,
required this.pdf
});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
// fields: Fields.fromJson(json['fields']),
recordid: json['id'] as String,
timecreated: json['createdTime'] as String,
title: json['fields']['field1'] as String,
content: json['fields']['field2'] as String,
imgurl: json['fields']['IMG'][0]['url'] as String,
pdf: json['fields']['PDF'] == null ? null : List<Map<String, dynamic>>.from(json['fields']['PDF']).map((dynamic value) => Pdf.fromJson(value)).toList()
);
}
Map<String, dynamic> toJson() => {
"recordid": recordid,
"timecreated": timecreated,
"title": title,
"content": content,
"imgurl": imgurl,
"pdf": pdf
// "fields": List<dynamic>.from(fields.map((x) => x.toJson())),
};
}
class Pdf {
Pdf({
required this.url,
required this.filename
});
Pdf.fromJson(Map<String, dynamic> json) :
url = json['url'],
filename = json['filename'];
final String? url;
final String? filename;
}
我沒有收到任何錯誤,但是當我嘗試在 UI 中使用 PDF URL 時,例如。在文本中:
ListTile(title: Text(post.pdf.url)),
我收到錯誤:
無法無條件訪問屬性“url”,因為接收者可以為“null”。
我的目標是在頁面上創建一個按鈕,當 PDF URL 存在時可以點擊。當它存在時,按鈕導航到使用 PDF URL 獲取和顯示 PDF 的 PDF 視圖。
有任何想法嗎?
uj5u.com熱心網友回復:
pdf 屬性可以為空,因此不能無條件訪問。這是假設您以某種方式將 pdf 不作為串列,否則您需要索引您的串列,您的代碼不完整。你可以嘗試做這樣的事情:
if (post.pdf != null) {
//wrap it with a button or whatever
return ListTile(title: Text(post.pdf!.url));
}
else {
return Text('no pdf');
}
uj5u.com熱心網友回復:
好吧,某事似乎有效,但仍然無法決議 pdf URL。
當 post.pdf != null 并且它可以作業時,我得到 Text "sth is there",但是當我更改為使用 post.pdf!.url 從模型中獲取價值時,我遇到了同樣的錯誤:
嘗試將名稱更正為現有 getter 的名稱,或定義一個名為“url”的 getter 或欄位。孩子:文本(post.pdf!.url));
這是一段代碼:
LayoutBuilder(builder: (context, constraints) {
if(post.pdf != null){
return ElevatedButton(onPressed: () => Navigator.of(context).push(
MaterialPageRoute(builder: (context) => PDFview(pdf: [])
)),
child:Text(post.pdf!.url));
}else{
return ElevatedButton(onPressed: null,
child:Text("no PDF"));
}
}
)
uj5u.com熱心網友回復:
PODO 中的修復對我有用。
這是我的問題的解決方案:)
pdf: json['fields']['PDF'] == null ? null : json['fields']['PDF'][0]['url'] as String,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/474145.html
下一篇:2x匹配標準顯示沒有結果
