首页 > 解决方案 > Flutter 在移动设备上使用 Floor 缓存数据,但也想为 Web 构建

问题描述

我想同时支持android和web。

但是我使用 Floor 来缓存数据,并且它在 web 上不受支持。所以我只想在 android 上进行数据库调用,我不想在 web 上缓存数据。我想忽略网络上的这些行。

我能以某种方式做到这一点吗?

void loadNews() async {
    emit(Loading());
    await newsCacheRepository.init();  //because of this line on web the data doesn't appear
    var articles = await newsCacheRepository.getArticles();
    emit(Loaded(articles));
    refreshNews();
  }

  Future<void> refreshNews() async {
    var articles = await newsNetworkRepository.getArticles();
    emit(Loaded(articles));
    newsCacheRepository.cacheArticles(articles);
  }

标签: flutterfloor

解决方案


您也可以使用支持 Web 的 Hive。或者您可以随时检查平台:

if(!kIsWeb){
 // Your code that doesn't support web
 }

但为了安全起见,您可以将代码包装在 try-catch 块中。

但我更喜欢使用支持 web 的 Hive。


推荐阅读