英文:
How a widget can get notification from a state change in a child widget?
问题
class MyWidget extends StatelessWidget {
const MyWidget({Key? key});
@override
Widget build(BuildContext context) {
return TextField(
onSubmitted: (text) {},
);
}
}
现在,我想在我的主要 Dart 文件中使用这个 MyWidget 类,但我也希望能够在从这个小部件触发 onSubmitted 时在我的主要 Dart 文件中使用这个 "text" 字符串。我该如何做到这一点?
英文:
Let's say I have the following widget in a dart file (as an example of the problem I am facing):
class MyWidget extends StatelessWidget {
const MyWidget({super.key});
@override
Widget build(BuildContext context) {
return TextField(
onSubmitted: (text) {},
);
}
}
Now, I want to use this MyWidget class in my main dart file, but I also want to be able to use this "text" string in my main dart file when onSubmitted is fired from this widget. How can I do that?
答案1
得分: 1
你可以在你的 Widget 内部使用回调函数:
class MyWidget extends StatelessWidget {
final Function(String) onSubmitted;
const MyWidget({Key key, this.onSubmitted}) : super(key: key);
@override
Widget build(BuildContext context) {
return TextField(
onSubmitted: onSubmitted,
);
}
}
以及如何使用你的 Widget:
class MyApp extends StatelessWidget {
void _onSubmitted(String text) {
// 对文本执行一些操作
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: MyWidget(onSubmitted: _onSubmitted),
);
}
}
英文:
You can use a callback function inside your Widget:
class MyWidget extends StatelessWidget {
final Function(String) onSubmitted;
const MyWidget({Key key, this.onSubmitted}) : super(key: key);
@override
Widget build(BuildContext context) {
return TextField(
onSubmitted: onSubmitted,
);
}
}
And how you can use your Widget:
class MyApp extends StatelessWidget {
void _onSubmitted(String text) {
// Do something with your text
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: MyWidget(onSubmitted: _onSubmitted),
);
}
}
答案2
得分: 1
你可以使用回调来解决这个问题:
void main() {
String mainText = "";
MyWidget(
/// 用于设置新值到 [mainText] 的回调
onSubmitted: (text) => mainText = text, // 分配值
);
}
class MyWidget extends StatelessWidget {
/// 用于获取小部件值更改的回调
final void Function(String value)? onSubmitted;
const MyWidget({super.key, this.onSubmitted});
@override
Widget build(BuildContext context) {
return TextField(
onSubmitted: onSubmitted,
);
}
}
英文:
You can use callbacks to solve this problem:
void main() {
String mainText = "";
MyWidget(
/// Callback use to set the new value on the [mainText]
onSubmitted: (text) => mainText = text, // assigning values
);
}
class MyWidget extends StatelessWidget {
/// Callback to get widget value changes
final void Function(String value)? onSubmitted;
const MyWidget({super.key, this.onSubmitted});
@override
Widget build(BuildContext context) {
return TextField(
onSubmitted: onSubmitted,
);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论