0

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?

Rodolfo
  • 96
  • 7

2 Answers2

1

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),
    );
  }
}
angwrk
  • 394
  • 1
  • 8
1

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