You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter执行build_runner无法生成Hive模型适配器文件

Flutter Hive适配器未生成问题排查

问题描述

在Flutter项目中使用Hive实现本地数据存储时,已将自定义Note模型改造为Hive适配格式,执行flutter pub run build_runner build命令后,包含适配器逻辑的note.g.dart文件始终未生成。

现有配置

note.dart 模型代码

import 'package:hive/hive.dart';

part 'note.g.dart';

class Note extends HiveObject{
  @HiveType(typeId: 0)
  Note({
    required this.id,
    required this.title,
    required this.content,
    required this.date,
    this.isPinned = false,
    this.isChecked = false,
  });

  @HiveField(0)
  late final DateTime id;

  @HiveField(1)
  late String title;

  @HiveField(2)
  late String content;

  @HiveField(3)
  late DateTime date;

  @HiveField(4)
  bool isPinned;

  @HiveField(5)
  bool isChecked;
}

pubspec.yaml 依赖配置

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.2
  provider: ^6.0.2
  intl: ^0.17.0
  very_good_analysis: ^1.0.0
  hive: ^2.2.2
  hive_flutter: ^1.1.0
  path_provider: ^2.0.2

dev_dependencies:
  flutter_test:
    sdk: flutter

  build_runner: ^2.1.11
  hive_generator: ^1.1.3 

排查步骤与解决方案

  • 核心问题:注解位置错误
    现有代码中@HiveType(typeId: 0)注解错误标注在了类的构造方法上,hive_generator只会扫描标注在类声明上的@HiveType注解来判断是否需要生成适配器,这是文件未生成的根本原因。
    修正后正确的类声明写法:
import 'package:hive/hive.dart';

part 'note.g.dart';

// @HiveType注解必须放在类定义上方
@HiveType(typeId: 0)
class Note extends HiveObject{
  Note({
    required this.id,
    required this.title,
    required this.content,
    required this.date,
    this.isPinned = false,
    this.isChecked = false,
  });

  @HiveField(0)
  late final DateTime id;

  @HiveField(1)
  late String title;

  @HiveField(2)
  late String content;

  @HiveField(3)
  late DateTime date;

  @HiveField(4)
  bool isPinned;

  @HiveField(5)
  bool isChecked;
}
  • 清理构建缓存重试
    修正代码后如果仍未生成文件,先执行命令清理旧构建缓存,再重新执行生成命令,避免缓存冲突:
flutter pub run build_runner clean
flutter pub get
flutter pub run build_runner build --delete-conflicting-outputs
  • 常规校验项
    • 确认note.dart存放在lib目录下,没有放到build、项目根目录等构建工具不会扫描的路径
    • 确认文件内part 'note.g.dart'的文件名拼写、大小写和实际文件完全匹配,避免大小写不匹配导致的生成失败
    • 现有依赖版本(hive ^2.2.2、hive_generator ^1.1.3、build_runner ^2.1.11)互相兼容,无需额外调整版本,注意不要跨大版本混用Hive相关依赖即可。

内容的提问来源于stack exchange,提问作者Kamlit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 01:21:40