1

The following Exception is thrown when I try to add an object Maybe I misunderstand how functions work. I couldn't find something helpful in documentation too

Unhandled Exception: Unhandled error PlatformException(-1, Attempting to create an object of type 'Country' with an existing primary key value ''., {
    RLMRealmCoreVersion = "";
    RLMRealmVersion = "3.17.3";
}, null) occurred in Instance of 'CountriesBloc'.

Here is my code . I have an CountriesToRealm event and I want to save my objects in flutter_realm when I add the event . I add it when I load countries by http request

  if (event is CountriesToRealm) {
      for (int i = 0; i < event.countries.length; ++i) {
        Country country = event.countries[i];

        print(country.name);

        if (country.name == null || country.name.isEmpty) {}
        final query = Query('Country').equalTo('name', country.name);
        final List all = await realm.objects(query);

        if (all.isEmpty) {
          await realm.createObject('Country', country.toMap(withId: true));
        }
      }
      final List allcountries = await event.realm.allObjects('Country');

      if (allcountries.length == event.countries.length) {
        yield CountriesAddedToRealmState();
      } else {
        yield FailedToAddCountriesState();
      }
    }

Also Realm Provider

import 'package:flutter/material.dart';
import 'package:flutter_realm/flutter_realm.dart';
import 'package:uuid/uuid.dart';

class RealmProvider extends StatefulWidget {
  final Widget Function(Realm) builder;

  const RealmProvider({this.builder}) : super();

  @override
  _RealmProviderState createState() => _RealmProviderState();
}

class _RealmProviderState extends State<RealmProvider> {
  Future<Realm> realm;

  @override
  void initState() {
    super.initState();
    final configuration = Configuration(inMemoryIdentifier: Uuid().v4());
    realm = Realm.open(configuration);
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<Realm>(
      future: realm,
      builder: (context, snapshot) {
        if (snapshot.data == null) {
          return Scaffold(
            appBar: AppBar(),
            body: Center(
              child: CircularProgressIndicator(),
            ),
          );
        }
        return widget.builder(snapshot.data);
      },
    );
  }
}

Thank you for your help

0 Answers0