我正在查看下面的 flutter 示例;
https://docs.flutter.dev/cookbook/forms/text-field-changes#interactive-example
它的代码如下;
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Retrieve Text Input',
home: MyCustomForm(),
);
}
}
// Define a custom Form widget.
class MyCustomForm extends StatefulWidget {
const MyCustomForm({super.key});
@override
State<MyCustomForm> createState() => _MyCustomFormState();
}
// Define a corresponding State class.
// This class holds data related to the Form.
class _MyCustomFormState extends State<MyCustomForm> {
// Create a text controller and use it to retrieve the current value
// of the TextField.
final myController = TextEditingController();
@override
void initState() {
super.initState();
// Start listening to changes.
myController.addListener(_printLatestValue);
}
@override
void dispose() {
// Clean up the controller when the widget is removed from the widget tree.
// This also removes the _printLatestValue listener.
myController.dispose();
super.dispose();
}
void _printLatestValue() {
print('Second text field: ${myController.text}');
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Retrieve Text Input'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
TextField(
onChanged: (text) {
print('First text field: $text');
},
),
TextField(
controller: myController,
),
],
),
),
);
}
}
以及以下方法;
@override
void dispose() {
// Clean up the controller when the widget is removed from the widget tree.
// This also removes the _printLatestValue listener.
myController.dispose();
super.dispose();
}
我在这里看到的myController
已经是_MyCustomFormState
类的实例。所以我的假设是一旦 MyCustomForm
小部件从小部件树中删除,它的所有实例成员都应该自动处置,对吗?但建议显式调用这些成员的 dispose
方法。
我可以了解为什么框架本身不执行此操作而我们需要处理它吗?我会理解它是否拥有该类范围之外的文件系统的句柄,但我在那里看到的范围之外没有该 Controller 的句柄。
最佳答案
当不再使用某个实例(例如您的 _MyCustomFormState
)时,它及其包含的所有引用都会自动被垃圾回收,例如您的 myController
。
但是,TextEditingController
实例附加的资源可能多于简单垃圾回收所能回收的资源。
因此建议在回收内存之前调用其dispose
方法。
与 C++ 等不同,Dart 的类没有析构函数的概念,因此需要调用 dispose
方法。
关于flutter - 为什么我们需要调用 `dispose` 方法,而成员是已处置类的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74876843/