FlutterIntermediate 2 min read

Return a result from a Flutter screen safely

Pass typed inputs to a destination and await a nullable result without using a stale BuildContext after navigation.

On this page

A destination should receive the data it needs through an explicit constructor or route parameter. Returning a result is useful for a selection flow: open a picker, wait for the user and update the original screen.

Treat cancellation as a normal result

A user can leave without choosing. That makes a route result nullable. Handling null explicitly is better than forcing every exit path to return a fabricated choice.

The fragment belongs in a callback inside a mounted screen. TopicPicker is a project widget with buttons that pop a selected string.

Worked example

This is a focused code fragment. Place it in the class or file described above; it is not a complete standalone app.

final selected = await Navigator.of(context).push<String>(
  MaterialPageRoute(builder: (_) => const TopicPicker()),
);
if (!context.mounted || selected == null) return;
ScaffoldMessenger.of(context).showSnackBar(
  SnackBar(content: Text('Selected: $selected')),
);

// Inside a TopicPicker button callback:
// Navigator.pop(context, 'State management');

Read the result

The caller decides how to apply the result. The picker only communicates the selection. After await, the original screen may have left the tree; the mounted check protects subsequent use of its context.

Trace the result in both directions

The caller starts a route and waits for a result. A selection on the destination pops that route with a string. Cancelling or using Back can return null instead. The caller applies a selected value only after it has checked both the result and whether the original screen is still present.

Keep the destination focused on choosing a value; it should not reach into arbitrary state fields of the calling page. This makes the picker reusable from another location.

Practise cancellation before adding success feedback. The dialog result pattern uses the same idea for a focused decision, while lifecycle ownership explains why callbacks can outlive a screen.

Practice and verification

Implement two choices and a cancel action. Test selecting, cancelling, using the system back gesture and leaving the original feature before the selection returns. Keep result handling in one place.

How this topic connects

Understand first

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.