参考:Flutter报错Target of URI hasn't been generated: - 简书 (jianshu.com)
首先需要确保你的项目根目录下的/jsons文件夹下:
ls .
Directory: C:\Users\Administrator\Documents\Flutter\项目根目录
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 2024-01-15 1:50 PM .dart_tool
d----- 2024-01-15 1:23 PM .idea
d----- 2024-01-15 1:25 PM android
d----- 2024-01-15 1:23 PM ios
d----- 2024-01-15 1:34 PM jsons
d----- 2024-01-15 1:26 PM lib
d----- 2024-01-15 1:23 PM linux
d----- 2024-01-15 1:23 PM macos
d----- 2024-01-15 1:23 PM test
d----- 2024-01-15 1:23 PM web
d----- 2024-01-15 1:23 PM windows
-a---- 2024-01-15 1:23 PM 745 .gitignore
-a---- 2024-01-15 1:23 PM 1668 .metadata
-a---- 2024-01-15 1:23 PM 1482 analysis_options.yaml
-a---- 2024-01-15 1:50 PM 16112 pubspec.lock
-a---- 2024-01-15 1:50 PM 4077 pubspec.yaml
-a---- 2024-01-15 1:23 PM 581 README.md
是否有对应的结构无误的.json 文件,我这里以user.json 为例,其中是定义要生成的User 实体类的字段:
{
"login": "TheFairyTale",
"avatar_url": "https://github.com/images/error/TheFairyTale.gif",
"type": "User",
"name?": "TheFairyTale",
"company?": "",
"blog?": "https://github.com/TheFairyTale",
"location?": "",
"email?": "TheFairyTale@github.com",
"hireable?": false,
"bio?": "",
"public_repos": 20,
"followers": 1,
"following": 0,
"created_at": "1970-01-01T00:00:00Z",
"updated_at": "1970-01-01T00:00:00Z",
"total_private_repos": 0,
"owned_private_repos": 0
}
如果确定以上文件与内容无误,则需要引入以下依赖:
dependencies:
flutter:
json_model: ^1.0.0
先使用命令来根据项目根目录下的jsons 文件夹生成对应lib/models 下的dart 类文件:
flutter packages pub run json_model
此时在你的项目目录下的/lib/models 文件夹下就已经有了根据/jsons 文件夹内.json文件描述所生成的类文件了:
ls .\lib\models\
Directory: C:\Users\Administrator\Documents\Flutter\项目根目录\lib\models
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 2024-01-15 2:01 PM 363 cacheConfig.dart
-a---- 2024-01-15 1:47 PM 98 index.dart
-a---- 2024-01-15 1:47 PM 431 profile.dart
-a---- 2024-01-15 1:47 PM 721 repo.dart
-a---- 2024-01-15 1:47 PM 629 user.dart
而如果你查看/lib/models 中生成的类文件,你会发现以下代码会报错,提示是
Target of URI doesn't exist: 'package:know_github_client_app/models/cacheConfig.g.dart.p'.
Try creating the file referenced by the URI, or try using a URI for a file that does exist.
part 'cacheConfig.g.dart';
这是因为在/lib/models 也就是类文件的同级目录下没有这个g.dart 文件,我们还需要添加以下依赖到pubspec.yml中:
dependencies:
json_annotation: ^4.8.1
dev_dependencies:
json_serializable: ^6.7.1
build_runner: ^2.4.8
再使用以下命令以根据类文件生成对应的g.dart文件:
flutter packages pub run build_runner build
完整代码与命令:
pubspec.yml:
environment:
sdk: '>=3.0.5 <4.0.0'
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
json_annotation: ^4.8.1
json_model: ^1.0.0
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^2.0.0
json_serializable: ^6.7.1
build_runner: ^2.4.8
第一步生成dart class 类文件命令:
flutter packages pub run json_model
第二步根据/lib/models 中的类文件生成对应的".g.class" 文件命令:
flutter packages pub run build_runner build