Flutter json_serializable

1 添加项目依赖

dev_dependencies:
  flutter_test:
    sdk: flutter
  build_runner: ^1.1.3
  json_serializable: ^3.2.0

2 创建实体类

  可以使用json_serializable库,将json 拷贝进去自动生成(简单json可以生成,在嵌套一层便会提示“不是一个正确的json”,不是特别好用)

将生成得subject.dart文件拷贝到项目中,提示如下异常

Flutter json_serializable_第1张图片

3 生成.g.dart文件

cd 你的工程目录

flutter packages pub run build_runner build    //使用 build_runner 生成 .g.dart 文件

flutter packages pub run build_runner wacth    //监控生成文件,如果有改动时自动生成/更新 .g.dart 文件

还没有生成.g.dart文件或者报错的运行下面的命令

cd 你的工程目录

flutter packages pub run build_runner build --delete-conflicting-outputs  //删除并重新创建.g.dart文件

没有生成的再运行一下

flutter packages pub run build_runner build

4、异常

F:\demo\flutter_demo\LeanDemo>flutter packages pub run build_runner build
[INFO] Generating build script...
[INFO] Generating build script completed, took 282ms

[INFO] Creating build script snapshot......
[INFO] Creating build script snapshot... completed, took 17.8s

[INFO] Initializing inputs
[INFO] Building new asset graph...
[INFO] Building new asset graph completed, took 1.0s

[INFO] Checking for unexpected pre-existing outputs....
[INFO] Found 1 declared outputs which already exist on disk. This is likely because the`.dart_tool/build` folder was deleted, or you are submitting generated files to your source repository.
[SEVERE] Conflicting outputs were detected and the build is unable to prompt for permission to remove them. These outputs must be removed manually or the build can be run with `--delete-conflicting-outputs`. The outputs are: lib/a
/model/entity/subject.g.dart
pub finished with exit code 78

找到一个已声明的输出,该输出已存在于磁盘上。这可能是因为“.dart_tool/build”文件夹已删除,或者您正在将生成的文件提交到源存储库。

运行flutter packages pub run build_runner build不光生成了xxxx.g.dart。同时还成了一个dart_tool/build目录,只运行app是没有问题的,之前xxxx.g.dart还是可用的。但是再生成新的xxxx.g.dart因为缺少之前生成dart_tool/build目下的文件就会报错。

解决:


//清除之前生成的文件,如果直接运行下面的不行。可以先尝试运行这个
 flutter packages pub run build_runner clean
//可以直接运行这个
 flutter packages pub run build_runner build --delete-conflicting-outputs

//在重新生成.g.dart
flutter packages pub run build_runner build

你可能感兴趣的:(异常,flutter)