Skip to content

Instantly share code, notes, and snippets.

@eli1stark
Created July 16, 2021 12:23
Show Gist options
  • Save eli1stark/e1f73752f756a57789ef80427c815232 to your computer and use it in GitHub Desktop.
Save eli1stark/e1f73752f756a57789ef80427c815232 to your computer and use it in GitHub Desktop.
Bug with dispose of StateNotfierProvider
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
class MyNotifier extends StateNotifier<int> {
MyNotifier() : super(0);
void add() => state++;
}
final myNotipod = StateNotifierProvider.autoDispose<MyNotifier, int>((ref) {
return MyNotifier();
});
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ProviderScope(
child: MaterialApp(
home: Scaffold(
body: HomeScreen(),
),
),
);
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return SafeArea(
child: Column(
children: [
TextButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ScreenA(),
),
);
},
child: Text('Push to Screen A'),
),
TextButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ScreenB(),
),
);
},
child: Text('Push to Screen B'),
),
],
),
);
}
}
class ScreenA extends HookWidget {
const ScreenA({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final pod = useProvider(myNotipod);
final podN = useProvider(myNotipod.notifier);
return Scaffold(
body: SafeArea(
child: Column(
children: [
TextButton(
onPressed: () => podN.add(),
child: Text('Add'),
),
Center(
child: Text('Data of A screen: $pod'),
),
],
),
),
);
}
}
class ScreenB extends HookWidget {
const ScreenB({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final pod = useProvider(myNotipod);
final podN = useProvider(myNotipod.notifier);
return Scaffold(
body: SafeArea(
child: Column(
children: [
TextButton(
onPressed: () => podN.add(),
child: Text('Add'),
),
Center(
child: Text('Data of B Screen: $pod'),
),
TextButton(
onPressed: () {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => ScreenA(),
),
);
},
child: Text('Push to Screen A'),
),
],
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment