【问题标题】:Flutter Hive store colorFlutter Hive 商店颜色
【发布时间】:2022-07-24 23:15:39
【问题描述】:

我需要将颜色存储在我的 Hive 数据库中以在我的电子商务应用程序中检索, 它给了我下面的错误,说我需要制作一个适配器,谁能告诉我如何制作一个颜色适配器?

part 'items_model.g.dart';

@HiveType(typeId: 0)
class Item {
  @HiveField(0)
  final String name;
  @HiveField(1)
  final double price;
  @HiveField(2)
  final String? description;
  @HiveField(3)
  var image;
  @HiveField(4)
  final String id;
  @HiveField(5)
  final String shopName;
  @HiveField(6)
  final List<Category> category;
  @HiveField(7)
  Color? color;
  @HiveField(8)
  int? quantity;
  Item({
    required this.category,
    required this.image,
    required this.name,
    required this.price,
    this.description,
    required this.id,
    required this.shopName,
    this.color,
    required this.quantity,
  });



}

有人知道如何生成或创建颜色适配器吗?因为我不知道怎么做

E/flutter ( 4621): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: HiveError: Cannot write, unknown type: MaterialColor. Did you forget to register an adapter?

【问题讨论】:

    标签: flutter dart flutter-hive


    【解决方案1】:

    我认为这里最简单的做法是存储颜色的int 值。

    这是一个例子。

    final colorValue = Colors.blue.value; // colorValue is an integer here
    

    所以你的Hive 颜色可以这样存储

    @HiveField(7)
    int? colorValue;
    

    然后,在您的应用中,当您从存储中创建颜色时,它会如下所示。

    final item = Item(...however you initialize your Item);
    
    final color = Color(item.colorValue);
    

    【讨论】:

      【解决方案2】:

      我为此困惑了一整天,我想出了如何去做。您应该像这样手动创建适配器:

        class ItemAdapter extends TypeAdapter<Item> {
        @override
        final typeId = 0;
      
        @override
        ThemeState read(BinaryReader reader) {
          return Item(
             color: Color(reader.readUint32()),
             //the rest of the fields here
           );
          }
      
        @override
        void write(BinaryWriter writer, ThemeState obj) {
          writer.writeUint32(obj.color.value);
          writer.writeString(obj.name);
          //the rest of the fields here
        }
      }
      

      Color 需要保存并写入为 Uint32 值,因为 Int32 值的范围只有 -2147483648 到 2147483647,无符号整数是 0 到 4294967295。Color() 的整数值可以超过 2147483647。如果 Uint32 是未使用,则您的值将无法正确存储,而是会保存奇怪的颜色。

      【讨论】:

        猜你喜欢
        • 2017-01-13
        • 2019-05-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-02
        相关资源
        最近更新 更多