Last active
January 15, 2023 00:17
-
-
Save gazialankus/3aefed6429499de5a939a6c50d158534 to your computer and use it in GitHub Desktop.
Riverpod bug
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'package:flutter_riverpod/flutter_riverpod.dart'; | |
final baseProvider = Provider<int>( | |
(ref) => 0, | |
); | |
final dependentProvider = Provider<String>( | |
(ref) { | |
final q = ref.watch(baseProvider); | |
return '$q'; | |
}, | |
dependencies: [baseProvider], | |
); | |
void main() { | |
runApp(const ProviderScope(child: AppRoot())); | |
} | |
class AppRoot extends StatelessWidget { | |
const AppRoot({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
return const MaterialApp( | |
home: MainPage(), | |
); | |
} | |
} | |
class MainPage extends StatefulWidget { | |
const MainPage({super.key}); | |
@override | |
State<MainPage> createState() => _MainPageState(); | |
} | |
class _MainPageState extends State<MainPage> { | |
var overridingValue = 1; | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
body: Center( | |
child: Column( | |
mainAxisSize: MainAxisSize.min, | |
children: [ | |
ProviderScope( | |
overrides: [ | |
baseProvider.overrideWithValue(overridingValue), | |
], | |
child: const MyConsumer(), | |
), | |
ElevatedButton( | |
onPressed: () { | |
setState(() {++overridingValue;}); | |
}, | |
child: const Text('increment (check the console)'), | |
), | |
], | |
), | |
), | |
); | |
} | |
} | |
class MyConsumer extends ConsumerWidget { | |
const MyConsumer({Key? key}) : super(key: key); | |
@override | |
Widget build(BuildContext context, WidgetRef ref) { | |
// the print line in listen below is executed only when this line is commented out | |
// If you uncomment this line, the print line is not executed anymore. | |
// | |
// final q = ref.watch(baseProvider); | |
ref.listen( | |
dependentProvider, | |
(previous, next) { | |
print('Listened to $previous -> $next. Try again after uncommenting line 76!'); | |
}, | |
); | |
return const SizedBox.shrink(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment