flutter - 抽象 - 如何为 Dart/Flutter 中的多种类型创建通用静态方法?

标签 flutter dart generics abstraction strong-typing

好吧,我正在尝试减少我的应用程序的大量样板代码。现在我认为需要进行一些重构和认真的抽象。

我想为我的数据库代码抽象 CRUD 操作。现在我正在创建一个单独的文件并为每个对象复制代码。我觉得必须有更好的方法,但我不知道如何在使用泛型抽象时保持显式类型安全。

我目前正在为每个对象执行类似的操作:
我非常确定您可以看到这会让某人发疯,我的应用程序中有 45 多个对象......而且许多对象比这更复杂。

abstract class HouseDatabaseAPI {

  /// CREATE EVENT
  /// Create house for authorized user
  static Future<void> createHouse({required House newHouse}) async {
    Box<House> houseBox = await Hive.openBox<House>('house_box');
    await houseBox.put(newHouse);
  }

  /// READ EVENT
  /// Get house for authorized user
  static Future<House?> getHouse() async {
    Box<House> houseBox = await Hive.openBox<House>('house_box');
    House? house = houseBox.getAt(0);
    return house;
  }

  /// UPDATE EVENT
  /// Update house for authorized user
  static Future<void> updateHouse({House? updatedHouse}) async {
    Box<House> houseBox = await Hive.openBox<House>('house_box');
    await houseBox.putAt(0, updatedHouse!);
  }

  /// DELETE EVENT
  /// Delete house from the local machine
  static Future<void> deleteGroup() async {
    Box<House> houseBox = await Hive.openBox<House>('house_box');
    await houseBox.deleteAt(0);
  }
}

当然,我希望这是严格类型化的而不是动态的。 我希望能够做什么而不是使用大量的流量控制语句(粗略的伪代码):


enum DatabaseAction {
   create,
   read,
   update,
   delete,
}

abstract class DatabaseRoutingAPI {
   
   Future<T> globalDatabaseCreateAction({
      DatabaseAction databaseAction,
      Object object,
      String databaseName,
      }) async {
         Box<T> houseBox = await Hive.openBox<T>(databaseName);
         await houseBox.put(object);
   }      

   ...

}

最佳答案

我将引导您从我的书签中找到有关 Hive 数据处理的一个很好的来源 -> here

在这里我将尝试回答您的问题:

abstract class Database {
  Box get box;
  T get<T>(String id);
  List<T> getAll<T>();
  Future<void> delete(String id);
  Future<void> deleteAll(List<String> keys);
  Future<void> addUpdate<T>(String id, T item);
}

class DatabaseImplementing implements Database {
  const DatabaseImplementing(this._box);
  
  final Box _box;
  
  @override
  Box get box => _box;

  @override
  T get<T>(String id) {
    try {
      final data = box.get(id);
      
      if (data == null) {
        throw Exception('$T not in the box.');
      }
      
      return data;
    } catch (_) {
      rethrow;
    }
  }

  @override
  List<T> getAll<T>() {
    try {
      final data = box.toMap().values;
      
      if (data.isEmpty) {
        throw Exception('$T not in the box.');
      }

      return data.toList().cast<T>();
    } catch (_) {
      rethrow;
    }
  }

  @override
  Future<void> delete(String id) async {
    try {
      await box.delete(id);
    } catch (_) {
      rethrow;
    }
  }

  @override
  Future<void> addUpdate<T>(String id, T item) async {
    try {
      await box.put(id, item);
    } catch (_) {
      rethrow;
    }
  }

  @override
  Future<void> deleteAll(List<String> keys) async {
    try {
      await box.deleteAll(keys);
    } catch (_) {
      rethrow;
    }
  }
}

当然还有很多其他方法可以做到这一点。

关于flutter - 抽象 - 如何为 Dart/Flutter 中的多种类型创建通用静态方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71701696/

相关文章:

dart - Flutter:根据值显示不同的图标

Flutter:在 BottomNavigationBar 中更新 currentIndex 时,PageView 的性能滞后(但如果我不更新 currentIndex,则没有滞后)

delphi - 维持秩序的键/值集合

java - 为什么有人声称 Java 的泛型实现很糟糕?

android - Flutter-SchedulerBinding,showDialoag,AlertDialog和WillPopScope的问题组合

ios - 无法验证下载服务器。您可能正在遭受中间人攻击

flutter - 如何在 Flutter 中移除 ListView 高亮颜色?

flutter - 需要像 Flutter 中的 Uber 那样的 Voip 通话

dart - 如何在文本中有一个小部件?

java - "&"或 ",": What is the difference between A<T extends I1 & I2> and A<T extends I1 , I2>