简体   繁体   中英

Create a Flutter plugin in swift to export realm data

We have a native iOS app that has a Realm database. Now we have developed a new Flutter app that will substitute the native iOS app. When an user upgrade native iOS app to the new Flutter app, we want to migrate the existing Realm database content into the new Sqflite database.

We have created a Flutter plugin with swift to export Realm data to json . At the moment, we were able to add RealmSwift dependency to the plugin, but when we run the below code, it throws Cannot find 'DeviceModel' in scope .

Any idea to get all rows from DeviceModel table? To acomplish that is necesary to add some Realm schema manually?

import Flutter
import UIKit
import RealmSwift

enum PluginError: Error {
  case notImplemented
}

public class SwiftRealmToJsonPlugin: NSObject, FlutterPlugin {
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "realm_to_json", binaryMessenger: registrar.messenger())
    let instance = SwiftRealmToJsonPlugin()
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    switch call.method {
      case "getPlatformVersion":
        result("iOS " + UIDevice.current.systemVersion)

      case "realmInfoExist":
        result(check_data())

      default:
        result(FlutterMethodNotImplemented)
    }
  }

  // check if Realm exists
  func check_data() -> Bool {
    let realm = try! Realm()
    let devices = realm.objects(DeviceModel.self)
  }
}

The solution was:

  • Change plugin language from Swift to Objective-C and copy and paste all Realm models.
  • Implement in each model class a method to generate a dictionary with it data.
  • Export dictionary to json.

Right now we are able to export Realm info into a json format. Next step is implement the migration logic to adapt a table-less structure to sql.

Thanks to @Jay to point me out the good direction to get a solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM