在Flutter中,我们需要为在dispose()
中创建的许多内容写下State
,例如
final _nameController = TextEditingController();
@override
void dispose() {
_nameController.dispose();
super.dispose();
}
因此,我想知道是否有一种方法可以消除这种需求,并自动调用该处理程序?
谢谢!
最佳答案
我找到了另一个解决方案:flutter_hooks
一个样本:
之前-
class Example extends StatefulWidget {
final Duration duration;
const Example({Key key, @required this.duration})
: assert(duration != null),
super(key: key);
@override
_ExampleState createState() => _ExampleState();
}
class _ExampleState extends State<Example> with SingleTickerProviderStateMixin {
AnimationController _controller;
@override
void initState() {
super.initState();
_controller = AnimationController(vsync: this, duration: widget.duration);
}
@override
void didUpdateWidget(Example oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.duration != oldWidget.duration) {
_controller.duration = widget.duration;
}
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container();
}
}
之后-
class Example extends HookWidget {
final Duration duration;
const Example({Key key, @required this.duration})
: assert(duration != null),
super(key: key);
@override
Widget build(BuildContext context) {
final controller = useAnimationController(duration: duration);
return Container();
}
}