Skip to content

Instantly share code, notes, and snippets.

@skurfuerst
Last active April 15, 2025 14:44
Show Gist options
  • Save skurfuerst/6431062c2b8aff81b41aeea61b9987aa to your computer and use it in GitHub Desktop.
Save skurfuerst/6431062c2b8aff81b41aeea61b9987aa to your computer and use it in GitHub Desktop.
riverpod - Notifiers are NOT recreated
//////////////////////////////////
// To run this gist, run: https://dartpad.dev/?id=6431062c2b8aff81b41aeea61b9987aa
//////////////////////////////////
import 'package:riverpod/riverpod.dart';
/// A Provider that reads a json file and decodes it into a [Configuration].
final authProvider = FutureProvider<String>((_) async {
print("executed authProvider");
return "my-auth-state";
});
final repositoryProvider = AsyncNotifierProvider<RepositoryNotifier, String>(
RepositoryNotifier.new,
);
class RepositoryNotifier extends AsyncNotifier<String> {
RepositoryNotifier() {
// ERKENNTNIS, UNERWARTET: dieser Constructor wird nur 1x aufgerufen,
// AUCH wenn der Provider invalidiert und neu erzeugt wird.
// => die build() Methode wird erneut aufgerufen, die Objektinstanz des Providers BLEIBT ABER DIE GLEICHE.
// => daher bleiben auch die Eigenschaften auf der Klasse die gleichen.
print("executed repositoryProvider::Constructor");
}
@override
Future<String> build() async {
// ERKENNTNIS: Build wird nach der Invalidierung erneut aufgerufen (as expected)
print("executed repositoryProvider::build 1");
/// Reads the configurations from [configurationProvider]. This is type-safe.
final authConfig = await ref.watch(authProvider.future);
print("executed repositoryProvider::build 2");
return authConfig + "processed";
}
}
Future<void> main() async {
// Where the state of our providers will be stored.
// Avoid making this a global variable, for testability purposes.
// If you are using Flutter, you do not need this.
final container = ProviderContainer();
print("executed main 1");
/// Obtains the [Repository]. This will implicitly load [Configuration] too.
var repository = await container.read(repositoryProvider.future);
print("executed main 2");
print("---INVALIDATING authProvider ---");
container.invalidate(authProvider);
print("executed main 3");
repository = await container.read(repositoryProvider.future);
/// Disposes the providers associated with [container].
container.dispose();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment