How to create multiple realm models in flutter and mongodb realm

26 Views Asked by At

I am new to flutter and realm. I have multiple forms in my project and I wanted to know what the best way to create the models is. I am working on a flutter app using the latest realm and flutter version.

I tried doing this but android studio just hangs for a very long time.

import 'package:realm/realm.dart';
part 'databaseModel.g.dart';

// Defining transactions model
@RealmModel()
class _Transaction{
  @PrimaryKey()
  late ObjectId id;

  late String selectedOption;
  late String transactionType ;
  late String currency ;
  late double rate ;
  late double amount ;
  late double total ;
  late String remarks ;
}

// Defining journal entry model
@RealmModel()
class _JournalEntry{
  @PrimaryKey()
  late ObjectId id;
  late String selectedOption;
  late String transactionType;
  late String currency;
  late String from;
  late String to;
  late double amount;
  late String remarks ;
}

//Defining new account model
@RealmModel()
class _NewAccount{
  @PrimaryKey()
  late ObjectId id;
  late String fullName;
  late int phoneNumber;
  late String email;
}
1

There are 1 best solutions below

0
Tim Kariuki On

Please note in the latest realm version does not specify the part file as part 'databaseModel.g.dart'; but part 'databaseModel.realm.dart';.

Also, if you expect your project to be big, it's always advisable to keep each model in it's own file.

If you have related models, always precede the name of the child model with $ instead of _. See example below:

--------------person.dart--------------

import 'package:realm/realm.dart';

part 'person.realm.dart';

@RealmModel()
class $Person {
  @PrimaryKey()
  late ObjectId id;
  late String firstName;
  late String lastName;
  late int? age;
}


--------------bike.dart--------------

import 'package:realm/realm.dart';
import 'path/to/person.dart';

part 'bike.realm.dart';

@RealmModel()
class _Bike {
  @PrimaryKey()
  late ObjectId id;
  late String name;
  late $Person? owner;
}

--------------bike_data_service.dart--------------
//In the data service config for bike, remember to include Person.schema

  final Configuration _config = Configuration.local([
    Bike.schema,
    Person.schema
  ]);