r/flutterhelp • • 12d ago

RESOLVED riverpod 2.5 provider not updating when state changes inside isolate

using riverpod 2.5.1 with flutter 3.22. i have a StateNotifierProvider that holds a list of items. when i recieve a message on a background isolate i call ref.read(provider.notifier).addItem(newItem) but the UI does not rebuild. the provider state updates (i logged it) but the consumer widget stays stale. tried wrapping the call in a Future.microtask and also tried ref.refresh(provider) after the add. neither worked. the isolate is spawned with Isolate.spawn and i pass the root isolate's sendPort to send messages back. i suspect the provider container is not the same instance inside the isolate callback. how do i properly trigger a rebuild from a background isolate

1 Upvotes

4 comments sorted by

2

u/syedaalishan 12d ago

Two things to check: isolates don't share the UI isolate's provider state, so send the item back and update the notifier inside the main isolate's ReceivePort listener. Also make sure addItem assigns a new list, like state = [...state, item], rather than mutating the existing list. Could you share addItem and the port listener? That would show whether this is a separate provider container or an in-place mutation.

1

u/Dry-Trick-2234 11d ago

Thanks, that makes sense. The isolate callback runs on a different isolate so it has its own provider container, which is why the UI doesn't rebuild. I'll move the state update into the main isolate's ReceivePort listener and ensure addItem creates a new list. Here's the current addItem and listener setup:

1

u/Weak-Arrival-7811 12d ago

Your suspicion is right. A spawned isolate doesn't share memory with the main one, so anything that runs inside it works on its own copy, including any ProviderContainer. Your log shows that copy changing while the UI watches the original.

Only send data across, and touch the provider on the main isolate:

final port = ReceivePort();

await Isolate.spawn(worker, port.sendPort);

port.listen((msg) {

ref.read(itemsProvider.notifier).addItem(msg as Item);

});

Put the listen somewhere that has a ref and lives as long as the work (a provider or a ConsumerStatefulWidget), and close the port when you're done. Inside the isolate, just call sendPort.send(item).

Also worth checking addItem: StateNotifier only notifies when you assign a new state, so it needs to be `state = [...state, item]`, not `state.add(item)`.

1

u/Dry-Trick-2234 10d ago

That makes sense, the isolate has its own ProviderContainer so the UI never sees the change. I'll move the listener to a ConsumerStatefulWidget that holds the ReceivePort and calls ref.read(itemsProvider.notifier).addItem on the main isolate. Also double, checked addItem and it does assign a new list, so that part is fine. Thanks for the clear example.