I'm having a hard time wrapping my head around working with mongodb inside flutter using riverpod.
There are two methods to obtain a connection,
one is using
var db = Db("mongodb://localhost:27017/mongo_dart-blog"); await db.open();
and other using var db = await Db.create("mongodb+srv://<user>:<password>@<host>:<port>/<database-name>?<parameters>"); await db.open();
I'm trying to work with the latter method since my instance is on atlas cloud but here the problem starts, since the latter methods is of type Future, I'm unable to use the db instance created here using a futureprovider as the type is asyncvalue.
I tried to work around with this without using a future provider, by using a basic provider for creating an instance and overriding with overrides like this:
final dataProvider = Provider<Db>((ref) => throw 'Database Not Initialized');
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
var db = Db.create('mongo-srv-string');
db.open();
runApp(
const ProviderScope(
overrides: [ dataProvider.overrideWithValue(db);]
child: Application(),
),
);
}
But it is throwing an error: MongoDart Error: Db is in the wrong state: State.OPENING
I consider myself a beginner in regards to working with both mongo and riverpod
so, would be really grateful if anyone have faced a similar issue or someone with more knowledgeable than me in these concepts help me solve this issue.
You need to wait for the database to open: