flutter 小部件如何从子小部件的状态变化中获得通知?[duplicate]

jxct1oxe  于 2023-03-13  发布在  Flutter
关注(0)|答案(2)|浏览(150)

此问题在此处已有答案

how can I call function with callback value from custom widget(1个答案)
How to pass callback in Flutter(3个答案)
3天前关闭。
假设我在一个dart文件中有以下小部件(作为我所面临问题的示例):

class MyWidget extends StatelessWidget {
  const MyWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return TextField(
      onSubmitted: (text) {},
    );
  }
}

现在,我想在我的主dart文件中使用这个MyWidget类,但我还想在onSubmitted从这个widget触发时,能够在我的主dart文件中使用这个“text”字符串。

9gm1akwq

9gm1akwq1#

您可以在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) {
    // Do something with your text
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: MyWidget(onSubmitted: _onSubmitted),
    );
  }
}
6za6bjd0

6za6bjd02#

您可以使用回调来解决此问题:

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,
    );
  }
}

相关问题