我对飞镖很陌生。
我在飞镖垫上看了一段udemy课程的教程视频
所以我也用飞镖写的。但它显示出错误的地方。
这是用udemy写的代码。
import 'dart:convert';
void main(){
var rawJson = '{"url": "https://helo.com","id": 2}';
var parsedJson = json.decode(rawJson);
var imageModel = new ImageModel.fromJson(parsedJson);
print(imageModel.url);
}
class ImageModel{
int id;
String url;
ImageModel.fromJson(parsedJson) {
id = parsedJson['id'];
url = parsedJson['url'];
}
ImageModel(this.id, this.url);
}在那个视频中,它运行,但对我来说,它显示错误为
Error compiling to JavaScript:
Info: Compiling with sound null safety
Warning: Interpreting this as package URI, 'package:dartpad_sample/main.dart'.
lib/main.dart:15:3:
Error: This constructor should initialize field 'id' because its type 'int' doesn't allow null.
ImageModel.fromJson(parsedJson) {
^
lib/main.dart:12:7:
Info: 'id' is defined here.
int id;
^^
lib/main.dart:15:3:
Error: This constructor should initialize field 'url' because its type 'String' doesn't allow null.
ImageModel.fromJson(parsedJson) {
^
lib/main.dart:13:10:
Info: 'url' is defined here.
String url;
^^^
Error: Compilation failed.我不知道是什么问题..。你们能帮我排除错误吗?
发布于 2022-02-09 04:46:57
发布于 2022-02-09 05:11:46
尝试使用空安全代码:例如:
int?字符串?url;
发布于 2022-02-09 05:24:13
,你会尝试像这样的
import 'dart:convert';
class ImageModel{
final int id;
final String url;
ImageModel({required this.id, required this.url});
factory ImageModel.fromJson(Map<String, dynamic> parsedJson) {
return ImageModel(
id: parsedJson['id'] as int,
url: parsedJson['url'] as String,
);
}
}
void main() {
var rawJson = '{"url": "https://helo.com","id": 2}';
var parsedJson = json.decode(rawJson);
print(parsedJson['url']);
print(parsedJson['id']);
}https://stackoverflow.com/questions/71043957
复制相似问题