Sub topic 11
Testing widgets that depend on services
This chapter assumes that you know basic Dart, async and await, and how to build stateless and stateful Flutter widgets. You should also know how to run flutter test and add packages in pubspec.yaml.
A widget often needs a service to do work outside the user interface. A service is a class that handles an external task, such as loading data, saving preferences, or calling an HTTP API. Testing the widget with a real service can make tests slow, unreliable, or dependent on network access.
Dependency injection is a design technique where a class receives its dependencies from outside instead of creating them internally. A widget can then receive a real service in the application and a predictable fake service in a test.
Prefer a service interface
An abstract class defines the operations that a service must provide. The widget depends on this interface, not on a particular implementation.
| Dependency choice | Test behavior | Typical use |
|---|---|---|
| Real service | May use a network, database, or device | End-to-end testing |
| Hand-written fake | Returns controlled values | Most widget tests |
| Mock object | Records and stubs interactions | Verifying calls |
The following file contains a complete widget test. The page receives a UserService, while the fake returns a fixed name without using a network.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
abstract class UserService {
Future<String> loadName();
}
class GreetingPage extends StatefulWidget {
const GreetingPage({required this.service, super.key});
final UserService service;
@override
State<GreetingPage> createState() => _GreetingPageState();
}
class _GreetingPageState extends State<GreetingPage> {
String? _name;
Object? _error;
@override
void initState() {
super.initState();
_loadName();
}
Future<void> _loadName() async {
try {
final name = await widget.service.loadName();
if (!mounted) return;
setState(() => _name = name);
} catch (error) {
if (!mounted) return;
setState(() => _error = error);
}
}
@override
Widget build(BuildContext context) {
if (_error != null) {
return const Center(child: Text('Could not load name'));
}
if (_name == null) {
return const Center(child: CircularProgressIndicator());
}
return Center(child: Text('Hello, $_name!'));
}
}
class FakeUserService implements UserService {
FakeUserService(this.name);
final String name;
int loadCount = 0;
@override
Future<String> loadName() async {
loadCount++;
return name;
}
}
void main() {
testWidgets('shows the name returned by the injected service',
(tester) async {
final service = FakeUserService('Ada');
await tester.pumpWidget(
MaterialApp(home: GreetingPage(service: service)),
);
expect(find.byType(CircularProgressIndicator), findsOneWidget);
await tester.pumpAndSettle();
expect(find.text('Hello, Ada!'), findsOneWidget);
expect(service.loadCount, 1);
});
}Control asynchronous work
The first pumpWidget builds the page and starts the asynchronous operation. The service has not necessarily completed at that point, so the loading indicator is visible. pumpAndSettle advances frames until scheduled work finishes and the interface settles.
A fake can also simulate failures:
- Return a value to test the success state.
- Throw an exception to test the error state.
- Delay a
Futureto test loading behavior. - Record calls when the test must check how often a service was used.
Keep fakes small. They should control the behavior relevant to the test, not reproduce the whole production service.
> callout note > Check mounted after awaiting a service call. A user may leave the page while the operation is running, and calling setState after disposal causes an error.
Exercise
Why should GreetingPage receive a UserService instead of creating one inside initState?
Show answer
Injection lets each test provide a fake with predictable results. Creating the service inside the widget would couple the test to the real implementation and its external effects.