![](/img/trans.png)
[英]Dart/Flutter remove boilerplate parameters in named constructor to reduce code size
[英]Reduce the boilerplate of dispose() in Flutter?
在 Flutter 中,我們需要為我們在State
中創建的許多東西寫下dispose()
,例如
final _nameController = TextEditingController();
@override
void dispose() {
_nameController.dispose();
super.dispose();
}
因此,我想知道是否有辦法消除這種需要,並自動調用 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();
}
}
你有幾個選擇:
State
中重寫dispose
方法是可以的,只需創建一個您需要處置的所有對象的列表,然后一次對它們調用dispose
。 像這樣的東西應該工作: @override
void dispose() {
[objectToDispose1, objectToDispose2, objectToDispose3].forEach((o) => o.dispose());
super.dispose();
}
State
,可能稱為DisposableState
。 這個抽象的 class 將有一個抽象的 getter 用於將對象作為List
進行處置。 然后,它將使用選項 1 中的上述方法在其 dispose 方法中引用該 getter: List get disposables;
@override
void dispose() {
disposables.forEach((o) => o.dispose());
super.dispose();
}
注意:您可以使用具有close()
而不是dispose()
的對象擴展這兩個選項,稍作修改會添加更多樣板:(
Unfortunately, I believe this is the shortest way to go about mass-disposing objects as they have to be "registered" for disposal/closing somewhere, and afaik, the Flutter framework does not provide any way to do this in the basic State
class.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.