如果需要的话,初始化这个函数的方法是什么?它应该传递给构造函数。
final void Function(String) onChanged;
这是部分代码:编译器抱怨未初始化的最终变量。
class CustomDynamicTextBox extends StatefulWidget {
final String? initialValue;
final void Function(String) onChanged;
@override
State<StatefulWidget> createState() => CustomDynamicTextBoxState();
}
现在,当我将它们传递给构造函数时,编译器将停止抱怨。为什么会这样?
class CustomDynamicTextBox extends StatefulWidget {
final String? initialValue;
final void Function(String) onChanged;
const CustomDynamicTextBox({this.initialValue, required this.onChanged});
@override
State<StatefulWidget> createState() => CustomDynamicTextBoxState();
}
您可以通过三种不同的方式来做到这一点,
使用 typedef 声明你的
void Function(String) onChanged
然后将其用作变量并为其分配值。
使用匿名方法。
直接使用你想要传递的方法作为 参数。
在此示例中,您可以看到按类型注释的三种方法。 第一个使用的是
typedef
用法:
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
typedef MyOnChanged = void Function(String value);
class CustomDynamicTextBox extends StatefulWidget {
final String? initialValue;
// final void Function(String value) onChanged;
// Toogle comments form this one and that above
final MyOnChanged onChanged;
const CustomDynamicTextBox({required this.initialValue, required this.onChanged, Key? key}) : super(key: key);
@override
_CustomDynamicTextBoxState createState() => _CustomDynamicTextBoxState();
}
class _CustomDynamicTextBoxState extends State<CustomDynamicTextBox> {
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () =>
widget.onChanged.call(" 'This value will be printed as the new value' and this: '${widget.initialValue}' is the initial value"),
child: const Text("Click me"),
);
}
}
void main() {
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('CustomDynamicTextBox Example'),
),
body: const StartWidget(),
),
));
}
// Typedef usage
class StartWidget extends StatelessWidget {
const StartWidget({super.key});
MyOnChanged get myOnChanged => (String value) {
if (kDebugMode) {
print("Value changed: $value");
}
};
@override
Widget build(BuildContext context) {
return CustomDynamicTextBox(initialValue: "Ciao da Italia", onChanged: myOnChanged);
}
}
// Anonymous usage
class StartWidget1 extends StatelessWidget {
const StartWidget1({super.key});
@override
Widget build(BuildContext context) {
return CustomDynamicTextBox(
initialValue: "Ciao da Italia",
onChanged: (String value) {
if (kDebugMode) {
print("Value changed: $value");
}
},
);
}
}
// Method usage
class StartWidget2 extends StatelessWidget {
const StartWidget2({super.key});
void printNewValue(String value) {
if (kDebugMode) {
print("Value changed: $value");
}
}
@override
Widget build(BuildContext context) {
return CustomDynamicTextBox(
initialValue: "Ciao da Italia",
onChanged: printNewValue,
);
}
}