Skip to content

Instantly share code, notes, and snippets.

@AAverin
Created March 8, 2023 09:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AAverin/a9727def4fb01c4514a3e7d8473683e8 to your computer and use it in GitHub Desktop.
Save AAverin/a9727def4fb01c4514a3e7d8473683e8 to your computer and use it in GitHub Desktop.
Bug listening to AsyncNotifierProvider
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final rnd = Random();
void main() => runApp(ProviderScope(child: MyApp()));
final counterProvider = AsyncNotifierProvider<Counter, List<int>>(() => Counter());
class Counter extends AsyncNotifier<List<int>> {
final List<int> values = [];
Counter();
add(int value) async {
state = await AsyncValue.guard(() async {
values.add(value);
return _readDatabase();
});
}
@override
FutureOr<List<int>> build() => _readDatabase();
Future<List<int>> _readDatabase() async => values;
}
final counterManagerProvider = Provider((ref) {
print("counterManagerProvider started listening");
ref.listen(counterProvider, (prev, next) async {
print("prev: $prev");
print("next: $next");
});
});
class MyApp extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
ref.watch(counterManagerProvider);
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Counter with Riverpod in Dartpad'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'You have pushed the button this many times:',
),
LayoutBuilder(builder: (context, box) {
final asyncValue = ref.watch(counterProvider);
return asyncValue.when(
data: (data) => Text(data.toString(), style: Theme.of(context).textTheme.headline4,),
loading: () => Text("Loading"),
error: (e,s) => Text("Error $e $s")
);
})
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async => await ref.read(counterProvider.notifier).add(rnd.nextInt(100)),
child: const Icon(Icons.add),
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment