我正在尝试使用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);
^^^^^^^^^^^^^^^^
答案 0 :(得分:0)
更改:
part 'Location.g.dart';
收件人:
part 'location.g.dart';