Skip to content

Instantly share code, notes, and snippets.

@mono0926
Last active June 19, 2019 02:25
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 mono0926/e11913bf6e9046dabdfb9c246568eaf1 to your computer and use it in GitHub Desktop.
Save mono0926/e11913bf6e9046dabdfb9c246568eaf1 to your computer and use it in GitHub Desktop.
一気にpopしたときのdisposeの順番が不定なので後ろの方に積まれた画面でdispose済みのListenableにアクセスしてしまってエラーになることがある問題
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() => runApp(App());
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Home')),
body: Center(
child: RaisedButton(
child: Text('→A'),
onPressed: () {
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => A()));
},
),
),
);
}
}
class A extends StatefulWidget {
@override
_AState createState() => _AState();
}
class _AState extends State<A> {
final _value = ValueNotifier<int>(0);
@override
void initState() {
super.initState();
print('A:initState');
}
@override
void dispose() {
print('A:dispose');
_value.dispose();
// This workaround fixes the problem
// Future.delayed(Duration(milliseconds: 50)).then((_) {
// _value.dispose();
// });
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('A')),
body: Center(
child: RaisedButton(
child: Text('→B'),
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => B(
value: _value,
),
),
);
},
),
),
);
}
}
class B extends StatefulWidget {
const B({
Key key,
@required this.value,
}) : super(key: key);
@override
_BState createState() => _BState();
final ValueListenable<int> value;
}
class _BState extends State<B> {
@override
void initState() {
super.initState();
print('B:initState');
}
@override
void dispose() {
print('B:dispose');
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('B')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ValueListenableBuilder(
valueListenable: widget.value,
builder: (context, value, child) {
return Text(value.toString());
},
),
RaisedButton(
child: Text('popToRoot'),
onPressed: () {
Navigator.of(context).popUntil((r) => r.isFirst);
},
),
],
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment