Mastering Flutter UI Testing: How to Verify Button States and Widget Properties
The Flutter news you actually need
No spam, ever. Unsubscribe in one click.
UI tests often break when a button changes state. A submit button may look grayed out, but gray is not a reliable test target. If you assert on opacity or color, you are testing the theme, not the behavior. The better question is: what property controls whether the user can interact with this widget right now?
In Flutter, many built-in buttons encode enabled state directly in their callbacks. An ElevatedButton is typically enabled when onPressed is not null; a disabled button usually sets onPressed to null. That gives you a simple, meaningful assertion: check the widget property, not the pixels.
Consider a profile form that enables a save button only after both fields are filled.
class ProfileForm extends StatefulWidget {
const ProfileForm({super.key});
@override
State<ProfileForm> createState() => _ProfileFormState();
}
class _ProfileFormState extends State<ProfileForm> {
final _nameController = TextEditingController();
final _emailController = TextEditingController();
@override
void dispose() {
_nameController.dispose();
_emailController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final isValid =
_nameController.text.trim().isNotEmpty &&
_emailController.text.trim().isNotEmpty;
return Scaffold(
appBar: AppBar(title: const Text('Profile')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
TextField(
controller: _nameController,
decoration: const InputDecoration(labelText: 'Display name'),
onChanged: (_) => setState(() {}),
),
const SizedBox(height: 12),
TextField(
controller: _emailController,
decoration: const InputDecoration(labelText: 'Email'),
onChanged: (_) => setState(() {}),
),
const SizedBox(height: 24),
ElevatedButton(
onPressed: isValid ? () => _save() : null,
child: const Text('Save profile'),
),
],
),
),
);
}
void _save() {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Profile saved')),
);
}
}
Now write a widget test that verifies the button state before and after input.
testWidgets('Save button starts disabled and enables after valid input', (tester) async {
await tester.pumpWidget(const MaterialApp(home: ProfileForm()));
final saveButton = find.widgetWithText(ElevatedButton, 'Save profile');
expect(saveButton, findsOneWidget);
expect(
tester.widget<ElevatedButton>(saveButton).onPressed,
isNull,
reason: 'Button should be disabled before required fields are filled',
);
await tester.enterText(find.byType(TextField).first, 'Ada');
await tester.enterText(find.byType(TextField).last, 'ada@example.com');
await tester.pump();
expect(
tester.widget<ElevatedButton>(saveButton).onPressed,
isNotNull,
reason: 'Button should be enabled once the form is valid',
);
await tester.tap(saveButton);
await tester.pumpAndSettle();
expect(find.text('Profile saved'), findsOneWidget);
});
This pattern works because tester.widget<T>() gives you the actual widget instance currently in the tree. You can inspect public properties, callbacks, controllers, decoration values, and custom configuration.
For other widgets, the same idea applies:
final emailField = tester.widget<TextField>(
find.byType(TextField).last,
);
expect(emailField.enabled, isTrue);
expect(emailField.controller?.text, 'ada@example.com');
expect(emailField.decoration?.labelText, 'Email');
If you use a custom button, expose the state clearly. A custom ActionButton with an enabled property is easier to test than one that only changes color internally.
class ActionButton extends StatelessWidget {
const ActionButton({
super.key,
required this.label,
required this.enabled,
required this.onPressed,
});
final String label;
final bool enabled;
final VoidCallback? onPressed;
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: enabled ? onPressed : null,
child: Text(label),
);
}
}
Then your test can check the contract:
expect(
tester.widget<ActionButton>(find.byType(ActionButton)).enabled,
isFalse,
);
A few mistakes to avoid:
- Do not assert that a disabled button looks faded. Visual styling changes with themes, platforms, and accessibility settings.
- Do not use
tester.tapas your primary disabled-state check. Disabled buttons may ignore pointer events, so the tap can be a no-op. - Always call
await tester.pump()after changing state that affects the widget under test. - Prefer
find.widgetWithText,find.byType, or keys when you need to inspect properties.
UI tests are most stable when they assert user-facing behavior through meaningful widget properties. For buttons, check the callback or enabled flag. For text fields, check the controller, decoration, and enabled state. That keeps your tests focused on what the app promises, not how it happens to render.
This blog is produced with the assistance of AI by a human editor. Learn more
Related Posts
Fixing Flutter TextField Issues: Preventing Input Lag, Lost Keystrokes, and Keyboard Glitches
Many Flutter developers struggle with common TextField issues like typing lag, lost keystrokes, or erratic keyboard behavior. This post will diagnose the root causes of these problems, including state management, TextEditingController misuse, and custom decorations, offering practical solutions for a smooth and reliable user input experience.
Choosing the Right Storage for Flutter: Beyond SharedPreferences for Persistent Data
Developers frequently struggle with persistent storage in Flutter, especially when dealing with OS-level backups and app reinstalls. This post will clarify the nuances of different storage solutions like `SharedPreferences`, `path_provider`, and `flutter_secure_storage`, focusing on how to correctly manage data lifetimes (per-install vs. per-user) and avoid issues like device IDs migrating to new phones or data being unexpectedly backed up.
Optimizing Flutter UI Performance: Solving `ImageFiltered` Lag and Smooth Blurring
Flutter's `ImageFiltered` can cause significant lag when blurring large or frequently changing content like text. This post will explain the performance bottlenecks, provide solutions like caching blurred outputs with `RepaintBoundary` or `SnapshotWidget`, and offer practical tips to ensure smooth UI effects without sacrificing frame rates.