Created
April 6, 2024 16:30
-
-
Save kranfix/5932289e661483930c5fae1a7c6ca1e2 to your computer and use it in GitHub Desktop.
Riverpod's provider doesn't store the state
This file contains hidden or 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'; | |
void main() => runApp(ProviderScope(child: const MyApp())); | |
final counterProvider = StateProvider<int>((ref) { | |
//final unsub = someStream.subscribe((val) => ref.state = va;); | |
//ref.onDispose(() => unsub()); | |
return 0; | |
}); | |
class MyApp extends StatelessWidget { | |
const MyApp({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
debugShowCheckedModeBanner: false, | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: const MyHomePage(title: 'Flutter Demo Home Page'), | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
final String title; | |
const MyHomePage({ | |
super.key, | |
required this.title, | |
}); | |
@override | |
State<MyHomePage> createState() => _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text(widget.title), | |
), | |
body: Center( | |
child: Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ | |
const CounterAndButton(), | |
ProviderScope( | |
overrides: [ | |
counterProvider.overrideWith((ref) => 4), | |
], | |
child: const CounterAndButton() | |
), | |
ProviderScope(child: const CounterAndButton()), | |
]), | |
), | |
); | |
} | |
} | |
class CounterAndButton extends ConsumerWidget { | |
const CounterAndButton(); | |
Widget build(BuildContext context, WidgetRef ref) { | |
final counter = ref.watch(counterProvider); | |
return Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: [ | |
const Text( | |
'Counter:', | |
), | |
Text( | |
'$counter', | |
style: Theme.of(context).textTheme.headlineMedium, | |
), | |
FloatingActionButton( | |
onPressed: () { | |
ref.read(counterProvider.notifier).state += 1; | |
}, | |
tooltip: 'Increment', | |
child: const Icon(Icons.add), | |
) | |
], | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment