Flutter-SEMBAST与Built_value的集成,如何将模型插入到sembast数据库中

时间:2019-10-14 10:15:09

标签: flutter flutter-dependencies flutter-test flutter-sliver sqflite

我尝试使用将Post对象插入SEMBAST数据库,但是需要toMap()才能插入数据库 请在下面找到我的代码

applicationContext
            .findBean(EmbeddedServer.class)
            .ifPresent(server -> {
                // start server
                long start = System.currentTimeMillis();
                server.start();
             });

我的数据源文件是


import 'package:built_collection/built_collection.dart';
import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';

import '../serializers.dart';
import 'articles.dart';

part 'news.g.dart';

abstract class News implements Built<News, NewsBuilder> {
  News._();

  factory News([updates(NewsBuilder b)]) = _$News;

  @BuiltValueField(wireName: 'status')
  String get status;
  @BuiltValueField(wireName: 'totalResults')
  int get totalResults;
  @BuiltValueField(wireName: 'articles')
  BuiltList<Articles> get articles;
  String toJson() {
    return json.encode(serializers.serializeWith(News.serializer, this));
  }

  static News fromJson(String jsonString) {
    return serializers.deserializeWith(
        News.serializer, json.decode(jsonString));
  }

  static Serializer<News> get serializer => _$newsSerializer;


}

但是插入语法 await _postsStore.add(await _db,post); 显示错误
import 'package:boilerplate/data/local/constants/db_constants.dart'; import 'package:boilerplate/models/news/news.dart'; import 'package:boilerplate/models/post/post.dart'; import 'package:boilerplate/models/post/post_list.dart'; import 'package:sembast/sembast.dart'; class NewsDataSource { // A Store with int keys and Map<String, dynamic> values. final _postsStore = intMapStoreFactory.store(DBConstants.STORE_NAME); // Private getter to shorten the amount of code needed to get the // singleton instance of an opened database. // Future<Database> get _db async => await AppDatabase.instance.database; // database instance final Future<Database> _db; // Constructor PostDataSource(this._db); // DB functions:-------------------------------------------------------------- Future insert(News news) async { return await _postsStore.add(await _db, post); } }

请帮助我解决问题

1 个答案:

答案 0 :(得分:1)

如前所述,sembast(如firestore和indexed_db)需要映射。您必须以兼容的方式使用build_value进行序列化。一种方法是在定义序列化程序时使用StandardJsonPlugin:

@SerializersFor([News])
final Serializers serializers =
    (_$serializers.toBuilder()..addPlugin(StandardJsonPlugin())).build();

然后您可以从新闻对象生成地图:

var map = serializers.serializeWith(News.serializer, news);

您的插入方法将是这样的:

Future insert(News news) async {
  var map = serializers.serializeWith(News.serializer, news);
  return await _postsStore.add(await _db, map);
}