I'm new in flutter and I have issue with parsing JSON on HTTP response.
I'm using Airtable backend, to store information about posts. These always contain images, and sometimes attachments - PDFs.
I built PODO, like this:
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;
}
I'm not getting any errors, but when I'm trying to use PDF URL in UI, eg. in Text:
ListTile(title: Text(post.pdf.url)),
I'm getting error:
The property 'url' can't be unconditionally accessed because the receiver can be 'null'.
I'm aiming to create a button on a page, that is clickable when PDF URL exists. When it exists, button navigates to PDF view that use PDF URL to get and display PDF.
Any ideas?
CodePudding user response:
The pdf attribute is nullable, hence it cannot be accessed unconditionally. This is assuming you somehow have the pdf not as a list, otherwise you would need to index your list, your code is incomplete. You could try to do something like this:
if (post.pdf != null) {
//wrap it with a button or whatever
return ListTile(title: Text(post.pdf!.url));
}
else {
return Text('no pdf');
}
CodePudding user response:
Well, sth seems to work, but still cannot parse pdf URL.
I'm getting Text "sth is there" when post.pdf != null and it works, but when I'm changing to get value from model using post.pdf!.url I'm getting same error:
Try correcting the name to the name of an existing getter, or defining a getter or field named 'url'. child:Text(post.pdf!.url));
Here's piece of code:
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"));
}
}
)