首页 > 解决方案 > 尝试使用 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);
                                   ^^^^^^^^^^^^^^^^

标签: jsonflutterflutter-dependencies

解决方案


改变:

part 'Location.g.dart';

到:

part 'location.g.dart';

推荐阅读