text
stringlengths
1
474
onPressed: () {
// Pop here with "Nope"...
},
child: const Text('Nope.'),
),
)
],
),
),
);
}
}<code_end>
<topic_end>
<topic_start>
4. When a button is tapped, close the selection screen
Now, update the onPressed() callback for both of the buttons.
To return data to the first screen,
use the Navigator.pop() method,
which accepts an optional second argument called result.
Any result is returned to the Future in the SelectionButton.<topic_end>
<topic_start>
Yep button
<code_start>ElevatedButton(
onPressed: () {
// Close the screen and return "Yep!" as the result.
Navigator.pop(context, 'Yep!');
},
child: const Text('Yep!'),
)<code_end>
<topic_end>
<topic_start>
Nope button
<code_start>ElevatedButton(
onPressed: () {
// Close the screen and return "Nope." as the result.
Navigator.pop(context, 'Nope.');
},
child: const Text('Nope.'),
)<code_end>
<topic_end>
<topic_start>
5. Show a snackbar on the home screen with the selection
Now that you’re launching a selection screen and awaiting the result,
you’ll want to do something with the information that’s returned.In this case, show a snackbar displaying the result by using the
_navigateAndDisplaySelection() method in SelectionButton:
<code_start>// A method that launches the SelectionScreen and awaits the result from
// Navigator.pop.
Future<void> _navigateAndDisplaySelection(BuildContext context) async {
// Navigator.push returns a Future that completes after calling
// Navigator.pop on the Selection Screen.
final result = await Navigator.push(
context,
MaterialPageRoute(builder: (context) => const SelectionScreen()),
);
// When a BuildContext is used from a StatefulWidget, the mounted property
// must be checked after an asynchronous gap.
if (!context.mounted) return;
// After the Selection Screen returns a result, hide any previous snackbars
// and show the new result.
ScaffoldMessenger.of(context)
..removeCurrentSnackBar()
..showSnackBar(SnackBar(content: Text('$result')));
}<code_end>
<topic_end>
<topic_start>
Interactive example
<code_start>import 'package:flutter/material.dart';
void main() {
runApp(
const MaterialApp(
title: 'Returning Data',
home: HomeScreen(),
),
);
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Returning Data Demo'),
),
body: const Center(
child: SelectionButton(),
),
);
}
}
class SelectionButton extends StatefulWidget {
const SelectionButton({super.key});
@override
State<SelectionButton> createState() => _SelectionButtonState();
}
class _SelectionButtonState extends State<SelectionButton> {
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {
_navigateAndDisplaySelection(context);