I received the error of `A ValueNotifier was used after being disposed.
Step to reproduce the error:
- I navigate to
menu.dartfromhomePage.dart. - Then, I go back from
menu.darttohomePage.dart. - I navigate again to
menu.dart. The error happened.
Error message
FlutterError (A `ValueNotifier<bool>` was used after being disposed.
Once you have called `dispose()` on a ValueNotifier<bool>, it can no longer be used.)
clearNotifier.dart
import 'package:flutter/material.dart';
ValueNotifier<bool> cancelListen =ValueNotifier(false);
homePage.dart
import 'package:project/pages/MenuFrame.dart';
...
IconButton(
icon: Image.asset('assets/image.png'),
iconSize: 50,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => ChangeNotifierProvider<ValueNotifier>(
create: (_) => cancelListen,
child: MenuFrame(
userId: widget.userId
)
),
// MaterialPageRoute(
// builder: (BuildContext context) => MenuFrame(
// userId: widget.userId,
// ),
),
)
.then(
);
},
)
menu.dart
import 'package:project/class/clearNotifier.dart';
class MenuFrame extends StatefulWidget {
const MenuFrame({Key key, this.userId}) : super(key: key);
final String userId;
@override
_MenuFrame createState() => _MenuFrameState();
}
@override
void dispose() {
cancelListen?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return ValueListenableBuilder(
valueListenable: cancelListen,
builder: (BuildContext context, bool toClearListen,Widget child){
....
});
}
How can I rebuild the ValueNotifier once it has been disposed?
CodePudding user response:
When you navigate from menu.dart back to homePage.dart, it call dispose function in menu.dart and your variable cancelListen was disposed. Therefore, when you navigate again to menu.dart, it will throw an error as you see.
Suggestion:
Do not pass variable cancelListen like that. You should create another ValueNotifier variable, I would temporary call it _cancelNotifier. You will pass the current value to homePage.dart:
MenuFrame(
userId: widget.userId,
value: cancelListen.value,
)
...............
late ValueNotifier<bool> _cancelNotifier;
initState() {
_cancelNotifier = ValueNotifier<bool>(widget.value);
}
