json - 尝试使用 json_serializable 包运行 android 模拟器时出现 Flutter 编译错误
问题描述
我正在尝试使用 json 可序列化包进行颤振,但出现编译错误。下面是我的模型文件的示例。
import 'package:json_annotation/json_annotation.dart';
part 'Location.g.dart';
@JsonSerializable()
class Location{
final String name;
final String location;
Location({this.name, this.location});
factory Location.fromJson(Map<String, dynamic> json) =>_$LocationFromJson(json);
Map<String, dynamic> toJson() => _$LocationToJson(this);
}
下面是生成的部分 Location.g.dart 文件
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'Location.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Location _$LocationFromJson(Map<String, dynamic> json) {
return Location(
name: json['name'] as String,
location: json['location'] as String,
);
}
Map<String, dynamic> _$LocationToJson(Location instance) => <String, dynamic>{
'name': instance.name,
'location': instance.location,
};
但是在尝试运行我的模拟器时,我得到了编译错误,
Compiler message:
lib/Models/location.dart:3:6: Error: Using 'lib/Models/Location.g.dart' as part of 'package:VendorApp/Models/location.dart' but its 'part of' declaration says 'package:VendorApp/Models/Location.dart'.
part 'Location.g.dart';
^
lib/Models/location.dart:12:58: Error: Method not found: '_$LocationFromJson'.
factory Location.fromJson(Map<String, dynamic> json) =>_$LocationFromJson(json);
^^^^^^^^^^^^^^^^^^
lib/Models/location.dart:13:36: Error: The method '_$LocationToJson' isn't defined for the class 'Location'.
- 'Location' is from 'package:VendorApp/Models/location.dart' ('lib/Models/location.dart').
Try correcting the name to the name of an existing method, or defining a method named '_$LocationToJson'.
Map<String, dynamic> toJson() => _$LocationToJson(this);
^^^^^^^^^^^^^^^^
解决方案
改变:
part 'Location.g.dart';
到:
part 'location.g.dart';
推荐阅读
- azure - 支持从 Azure 到 QRadar 的事件
- javascript - Webpack5 在运行时无法编译图像并引发错误
- javascript - 如何将文本从前 50 个单词缩短并将其放回细节函数 Javascript?
- jquery - 当超过 10k 数据时,Laravel 数据表加载缓慢
- php - 合并 2 个 json 文件,其中并非所有数据都匹配
- pine-script - 如何在 PineScript 中获取蜡烛的百分比变化数据?
- android - 我的 android studio 中很少有 xml 文件显示一些奇怪的文本
- javascript - 反应强制在按钮单击时完全重新渲染
- zeebe - 如何在 1.1.0 稳定版的 zeebe 客户端中完成“USER_TASK”?
- mongodb - 连接完成后如何创建一个简单的检索 API?