【问题标题】:Flutter compilation error when trying to run android emulator with json_serializable package尝试使用 json_serializable 包运行 android 模拟器时出现 Flutter 编译错误
【发布时间】:2020-09-30 16:37:42
【问题描述】:

我正在尝试使用 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);
                                   ^^^^^^^^^^^^^^^^

【问题讨论】:

    标签: json flutter flutter-dependencies


    【解决方案1】:

    改变:

    part 'Location.g.dart';
    

    到:

    part 'location.g.dart';
    

    【讨论】:

    • 谢谢,我没注意到文件名是小写的
    • 编译器错误消息已经解释了一切,它甚至在L 上放置了一个^,以便您知道。
    • 虽然每次我运行它都会显示一个弹出警告说存在构建错误但是如果我忽略它们应用程序运行,有什么办法解决这个问题?
    猜你喜欢
    • 1970-01-01
    • 2021-07-19
    • 2017-09-11
    • 2022-12-29
    • 2020-11-13
    • 2021-09-05
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多