Ошибка улья — Тип ‘TypeAdapter’ объявлен с параметрами типа 0, но были заданы аргументы типа 1

#android #ios #flutter #dart #hive

Вопрос:

Я работаю с моделями ульев, в которых я правильно назначил @HiveType(typeId: x) каждому классу, хотя при запуске

  flutter packages pub run build_runner build
 

Я получаю ошибку в сгенерированном файле для моделей с типом от 2 до 10, ниже приведена ошибка, эти модели с типом от 2 до 10 были добавлены позже, поэтому мне нужно удалить предыдущий сгенерированный файл и повторить команду, а также сгенерированные адаптеры типов для типа 0 и типа 1, т. Е. Модуль И Данные пользователя. В этом нет проблемы.

 The type 'TypeAdapter' is declared with 0 type parameters, but 1 type arguments were given. 
Try adjusting the number of type arguments to match the number of type 
parameters.dart(wrong_number_of_type_arguments)
 

Тип 'TypeAdapter' объявлен с параметрами типа 0, но были заданы аргументы типа 1. Попробуйте настроить количество аргументов типа в соответствии с количеством параметров типа.dart(неверное_номер_от_типа_аргументы)

 This issue is for only models with typeId:2 to typeId:10
 

Ниже приведены мои модели с @HiveType и @HiveField,

Файл 1 Модели

       @HiveType(typeId: 0)
      class UserData {
        @HiveField(0)
        String token;
        int userID;
        @HiveField(1)
        String firstName;

        UserData({
          this.userID,
          this.firstName,
        });
      }

      @HiveType(typeId: 1)
      class Module {
        @HiveField(0)
        int moduleID;
        @HiveField(1)
        String moduleName;

        Module({
          this.moduleID,
          this.moduleName,
        });
      }
 

Файл 2 Модели

     @HiveType(typeId: 2)
    class ExamData {
      @HiveField(0)
      int moduleID;
      @HiveField(1)
      int broadcastID;

      ExamData(
          {this.moduleID,
          this.broadcastID,});
    }


    @HiveType(typeId: 3)
    class Section {
      @HiveField(0)
      int sectionID;
      @HiveField(1)
      String title;

      Section(
          {this.sectionID,
          this.title
      });
    }

    @HiveType(typeId: 4)
    class Question {
      @HiveField(0)
      int questionID;
      @HiveField(1)
      String title;

      Question(
          {this.questionID,
          this.title});
    }

    @HiveType(typeId: 5)
    class Type {
      @HiveField(0)
      int typeId;
      @HiveField(1)
      String name;

      Type({this.typeId, this.name});
    }

    @HiveType(typeId: 6)
    class Answer {
      @HiveField(0)
      int answerID;
      @HiveField(1)
      String title;

      Answer({this.answerID, this.title});
    }

    @HiveType(typeId: 7)
    class FileInfo {
      @HiveField(0)
      int fileID;
      @HiveField(1)
      String type;

      FileInfo(
          {this.fileID,
          this.type});
    }

    @HiveType(typeId: 8)
    class Meta {
      @HiveField(0)
      String tempFieldForHiveTest;
      @HiveField(1)
      List<Tag> tags;

      Meta({this.tags, this.tempFieldForHiveTest: ""});
    }

    @HiveType(typeId: 9)
    class Tag {
      @HiveField(0)
      int tagID;
      @HiveField(1)
      int moduleID;

      Tag(
          {this.tagID,
          this.moduleID,});
    }

    @HiveType(typeId: 10)
    class SectionStatus {
      @HiveField(0)
      Section section;
      @HiveField(1)
      bool isAttempted;
      SectionStatus({this.section, this.isAttempted});
    }
 

ниже приведены мои зависимости от разработчиков

 dev_dependencies:
  hive_generator: ^1.1.1
  build_runner: ^2.0.6
  flutter_launcher_icons: ^0.9.2
 

Ответ №1:

Я получил ответ на свой вопрос на github в репо Hive, благодаря Матеусу Баумгартену, https://github.com/hivedb/hive/issues/811

 I was having a model called Type;
 

Когда Hive пытается создать адаптер, он использует имя вашей модели суффикс адаптера; например

 class TypeAdapter extends TypeAdapter<Type> {}
 

Созданный адаптер затем находится в области действия, и dart не может понять, что адаптер типа, который пытаются расширить другие классы, происходит из Hive.

Таким образом, добавление имени адаптации решило проблему,

   /// In your models file
  @HiveType(typeId: 5, adapterName: "MyTypeAdapter")
  class Type {
     /* ... */
  }
 

в каком сгенерированном файле будет модель типа с именем MyTypeAdapter, которая будет реализовывать нашу модель типа

     class MyTypeAdapter extends TypeAdapter<Type> {
      @override
      final int typeId = 5;

      @override
      Type read(BinaryReader reader) {
        final numOfFields = reader.readByte();
        final fields = <int, dynamic>{
          for (int i = 0; i < numOfFields; i  ) reader.readByte(): reader.read(),
        };
        return Type(
          typeID: fields[0] as int,
          name: fields[1] as String,
        );
      }
    }