Many of the Widgets we build not only display information, but also respond touser interaction. This includes buttons that users can tap on, dragging itemsacross the screen, or entering text into aTextField
.
In order to test these interactions, we need a way to simulate them in the testenvironment. To do so, we can use theWidgetTester
class provided by theflutter_test
library.
The WidgetTester
provides methods for entering text, tapping, and dragging.
enterText
tap
drag
In many cases, user interactions will update the state of our app. In the testenvironment, Flutter will not automatically rebuild widgets when the statechanges. To ensure our Widget tree is rebuilt after we simulate a userinteraction, we must call thepump
orpumpAndSettle
methods provided by theWidgetTester
.
Directions
- Create a Widget to test
- Enter text in the text field
- Ensure tapping a button adds the todo
- Ensure swipe-to-dismiss removes the todo
1. Create a Widget to test
For this example, we’ll create a basic todo app. It will have three mainfeatures that we’ll want to test:
- Enter text into a
TextField
- Tapping a
FloatingActionButton
adds the text to a list of todos Swipe-to-dismiss removes the item from the listTo keep the focus on testing, this recipe will not provide a detailed guide onhow to build the todo app. To learn more about how this app is built, please seethe relevant recipes:
- Handling Taps
- Create a basic list
- Implement Swipe to Dismiss
class TodoList extends StatefulWidget {
@override
_TodoListState createState() => _TodoListState();
}
class _TodoListState extends State<TodoList> {
static const _appTitle = 'Todo List';
final todos = <String>[];
final controller = TextEditingController();
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _appTitle,
home: Scaffold(
appBar: AppBar(
title: Text(_appTitle),
),
body: Column(
children: [
TextField(
controller: controller,
),
Expanded(
child: ListView.builder(
itemCount: todos.length,
itemBuilder: (BuildContext context, int index) {
final todo = todos[index];
return Dismissible(
key: Key('$todo$index'),
onDismissed: (direction) => todos.removeAt(index),
child: ListTile(title: Text(todo)),
background: Container(color: Colors.red),
);
},
),
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
todos.add(controller.text);
controller.clear();
});
},
child: Icon(Icons.add),
),
),
);
}
}
2. Enter text in the text field
Now that we have a todo app, we can begin writing our test! In this case, we’llstart by entering text into the TextField
.
We can accomplish this task by:
- Building the Widget in the Test Environment
- Using the
enterText
method from theWidgetTester
testWidgets('Add and remove a todo', (WidgetTester tester) async {
// Build the Widget
await tester.pumpWidget(TodoList());
// Enter 'hi' into the TextField
await tester.enterText(find.byType(TextField), 'hi');
});
Note: This recipe builds upon previous Widget testing recipes. To learn thecore concepts of Widget testing, see the following recipes:
3. Ensure tapping a button adds the todo
After we’ve entered text into the TextField
, we’ll want to ensure that tappingthe FloatingActionButton
adds the item to the list.
This will involve three steps:
- Tap the add button using the
tap
method - Rebuild the Widget after the state has changed using the
pump
method - Ensure the list item appears on screen
testWidgets('Add and remove a todo', (WidgetTester tester) async {
// Enter text code...
// Tap the add button
await tester.tap(find.byType(FloatingActionButton));
// Rebuild the Widget after the state has changed
await tester.pump();
// Expect to find the item on screen
expect(find.text('hi'), findsOneWidget);
});
4. Ensure swipe-to-dismiss removes the todo
Finally, we can ensure that performing a swipe-to-dismiss action on the todoitem will remove it from the list. This will involve three steps:
- Use the
drag
method to perform a swipe-to-dismiss action. - Use the
pumpAndSettle
method to continually rebuild our Widget tree until the dismiss animation is complete. - Ensure the item no longer appears on screen.
testWidgets('Add and remove a todo', (WidgetTester tester) async {
// Enter text and add the item...
// Swipe the item to dismiss it
await tester.drag(find.byType(Dismissible), Offset(500.0, 0.0));
// Build the Widget until the dismiss animation ends
await tester.pumpAndSettle();
// Ensure the item is no longer on screen
expect(find.text('hi'), findsNothing);
});
Complete example
Once we’ve completed these steps, we should have a working app with a test toensure it works correctly!
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Add and remove a todo', (WidgetTester tester) async {
// Build the Widget
await tester.pumpWidget(TodoList());
// Enter 'hi' into the TextField
await tester.enterText(find.byType(TextField), 'hi');
// Tap the add button
await tester.tap(find.byType(FloatingActionButton));
// Rebuild the Widget with the new item
await tester.pump();
// Expect to find the item on screen
expect(find.text('hi'), findsOneWidget);
// Swipe the item to dismiss it
await tester.drag(find.byType(Dismissible), Offset(500.0, 0.0));
// Build the Widget until the dismiss animation ends
await tester.pumpAndSettle();
// Ensure the item is no longer on screen
expect(find.text('hi'), findsNothing);
});
}
class TodoList extends StatefulWidget {
@override
_TodoListState createState() => _TodoListState();
}
class _TodoListState extends State<TodoList> {
static const _appTitle = 'Todo List';
final todos = <String>[];
final controller = TextEditingController();
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _appTitle,
home: Scaffold(
appBar: AppBar(
title: Text(_appTitle),
),
body: Column(
children: [
TextField(
controller: controller,
),
Expanded(
child: ListView.builder(
itemCount: todos.length,
itemBuilder: (BuildContext context, int index) {
final todo = todos[index];
return Dismissible(
key: Key('$todo$index'),
onDismissed: (direction) => todos.removeAt(index),
child: ListTile(title: Text(todo)),
background: Container(color: Colors.red),
);
},
),
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
todos.add(controller.text);
controller.clear();
});
},
child: Icon(Icons.add),
),
),
);
}
}