Flutter -integration of SEMBAST with built_value , how to insert the Model into the sembast db

Issue

I tried to use insert the Post object into SEMBAST Database but it is required the toMap() to insert into DB
Please find my Code below


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;


}

and my data source file is

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);
  }


}

But the Insert syntax await _postsStore.add(await _db, post); shows an error
Future<int> StoreRef.add(DatabaseClient client, Map<String, dynamic> value)

Please help me how to solve it

Solution

As stated, sembast, like firestore and indexed_db expect a map. You must serialize using built_value in a compatible way. One way is to use the StandardJsonPlugin when you define your serializer:

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

You can then generate a map from your news object:

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

Your insert method will then be something like that:

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

Answered By – alextk

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.