How to test a Flutter app

    1. Introduction

    Flutter is Google's UI toolkit for building beautiful, natively compiled applications for mobile, web, and desktop from a single codebase.

    In this codelab, you'll build and test a simple Flutter app. The app will use theProvider package for managing state.

    What you'll learn

    • How to create widget tests using the widget testing framework
    • How to create an integration test to test the app's UI and performance using theintegration_test library
    • How to test data classes (providers) with the help of unit tests

    What you'll build

    In this codelab, you'll start by building a simple application with a list of items. We provide the source code for you so you can get right to the testing. The app supports the following operations:

    • Adding the items to favorites
    • Viewing the list of favorites
    • Removing items from the favorites list

    Once the app is complete, you will write the following tests:

    • Unit tests to validate the add and remove operations
    • Widgets tests for the home and favorites pages
    • UI and performance tests for the entire app using integration tests

    GIF of the app running on Android

    What would you like to learn from this codelab?

    I'm new to the topic, and I want a good overview.I know something about this topic, but I want a refresher.I'm looking for an example code to use in my project.I'm looking for an explanation of something specific.

    2. Set up your Flutter development environment

    You need two pieces of software to complete this lab—theFlutter SDK andan editor.

    You can run the codelab using any of these devices:

    • A physicalAndroid oriOS device connected to your computer and set to Developer mode.
    • The iOS simulator (requires installing Xcode tools).
    • TheAndroid Emulator (requires setup in Android Studio).
    • A browser (Chrome is required for debugging).
    • As aWindows,Linux, ormacOS desktop application. You must develop on the platform where you plan to deploy. So, if you want to develop a Windows desktop app, you must develop on Windows to access the appropriate build chain. There are operating system-specific requirements that are covered in detail ondocs.flutter.dev/desktop.

    3. Getting started

    Create a new Flutter app & update dependencies

    This codelab focuses on testing a Flutter mobile app. You will quickly create the app to be tested using source files that you copy and paste. The rest of the codelab then focuses on learning different kinds of testing.

    a3c16fc17be25f6c.pngCreate a simple templated Flutter app, either using the instructions inGetting Started with your first Flutter app, or on the command line as follows.

    $ flutter create --empty testing_appCreating project testing_app...Resolving dependencies in `testing_app`... Downloading packages... Got dependencies in `testing_app`.Wrote 128 files.All done!You can find general documentation for Flutter at: https://docs.flutter.dev/Detailed API documentation is available at: https://api.flutter.dev/If you prefer video documentation, consider: https://www.youtube.com/c/flutterdevIn order to run your empty application, type:  $ cd testing_app  $ flutter runYour empty application code is in testing_app/lib/main.dart.

    a3c16fc17be25f6c.pngAdd pub dependencies on the command line.

    • provider for easy state management,
    • integration_test for self-driving testing of Flutter code on devices and emulators,
    • flutter_driver for an advanced API to test Flutter applications that run on real devices and emulators,
    • test for general test tooling,
    • go_router for handling app navigation.
    $ cd testing_app$ flutter pub add provider go_router dev:test 'dev:flutter_driver:{"sdk":"flutter"}' 'dev:integration_test:{"sdk":"flutter"}'Resolving dependencies... Downloading packages... + _fe_analyzer_shared 67.0.0 (68.0.0 available)+ analyzer 6.4.1 (6.5.0 available)+ args 2.5.0+ convert 3.1.1+ coverage 1.7.2+ crypto 3.0.3+ file 7.0.0+ flutter_driver 0.0.0 from sdk flutter+ flutter_web_plugins 0.0.0 from sdk flutter+ frontend_server_client 4.0.0+ fuchsia_remote_debug_protocol 0.0.0 from sdk flutter+ glob 2.1.2+ go_router 14.0.2+ http_multi_server 3.2.1+ http_parser 4.0.2+ integration_test 0.0.0 from sdk flutter+ io 1.0.4+ js 0.7.1  leak_tracker 10.0.4 (10.0.5 available)  leak_tracker_flutter_testing 3.0.3 (3.0.5 available)+ logging 1.2.0  material_color_utilities 0.8.0 (0.11.1 available)  meta 1.12.0 (1.14.0 available)+ mime 1.0.5+ nested 1.0.0+ node_preamble 2.0.2+ package_config 2.1.0+ platform 3.1.4+ pool 1.5.1+ process 5.0.2+ provider 6.1.2+ pub_semver 2.1.4+ shelf 1.4.1+ shelf_packages_handler 3.0.2+ shelf_static 1.1.2+ shelf_web_socket 1.0.4+ source_map_stack_trace 2.1.1+ source_maps 0.10.12+ sync_http 0.3.1+ test 1.25.2 (1.25.4 available)  test_api 0.7.0 (0.7.1 available)+ test_core 0.6.0 (0.6.2 available)+ typed_data 1.3.2+ watcher 1.1.0+ web 0.5.1+ web_socket_channel 2.4.5+ webdriver 3.0.3+ webkit_inspection_protocol 1.2.1+ yaml 3.1.2Changed 44 dependencies!9 packages have newer versions incompatible with dependency constraints.Try `flutter pub outdated` for more information.

    The following dependencies should have been added to yourpubspec.yaml:

    pubspec.yaml

    name: testing_appdescription: "A new Flutter project."publish_to: 'none'version: 0.1.0environment:  sdk: '>=3.4.0-0 <4.0.0'dependencies:  flutter:    sdk: flutter  go_router: ^14.0.2  provider: ^6.1.2dev_dependencies:  flutter_test:    sdk: flutter  flutter_lints: ^3.0.0  test: ^1.25.2  flutter_driver:    sdk: flutter  integration_test:    sdk: flutterflutter:  uses-material-design: true

    a3c16fc17be25f6c.pngOpen the project in yourcode editor of choice, and run the app. Alternatively, run it on the command line as follows.

    $ flutter run

    4. Build the app

    Next, you'll build out the app so that you can test it. The app contains the following files:

    • lib/models/favorites.dart - creates the model class for favorites list
    • lib/screens/favorites.dart - creates the layout for the favorites list
    • lib/screens/home.dart - creates a list of items
    • lib/main.dart - the main file where the app starts

    First, create theFavorites model inlib/models/favorites.dart

    a3c16fc17be25f6c.pngCreate a new directory namedmodels in thelib directory, and then create a new file namedfavorites.dart. In that file add the following code:

    lib/models/favorites.dart

    import'package:flutter/material.dart';///The[Favorites]classholdsalistoffavoriteitemssavedbytheuser.classFavoritesextendsChangeNotifier{finalList<int>_favoriteItems=[];List<int>getitems=>_favoriteItems;voidadd(intitemNo){_favoriteItems.add(itemNo);notifyListeners();}voidremove(intitemNo){_favoriteItems.remove(itemNo);notifyListeners();}}

    Add the Favorites page inlib/screens/favorites.dart

    a3c16fc17be25f6c.pngCreate a new directory namedscreens in thelib directory, and in that directory create a new file namedfavorites.dart. In that file add the following code:

    lib/screens/favorites.dart

    import'package:flutter/material.dart';import'package:provider/provider.dart';import'../models/favorites.dart';classFavoritesPageextendsStatelessWidget{constFavoritesPage({super.key});staticStringrouteName='favorites_page';@overrideWidgetbuild(BuildContextcontext){returnScaffold(appBar:AppBar(title:constText('Favorites'),),body:Consumer<Favorites>(builder:(context,value,child)=>ListView.builder(itemCount:value.items.length,padding:constEdgeInsets.symmetric(vertical:16),itemBuilder:(context,index)=>FavoriteItemTile(value.items[index]),),),);}}classFavoriteItemTileextendsStatelessWidget{constFavoriteItemTile(this.itemNo,{super.key});finalintitemNo;@overrideWidgetbuild(BuildContextcontext){returnPadding(padding:constEdgeInsets.all(8.0),child:ListTile(leading:CircleAvatar(backgroundColor:Colors.primaries[itemNo%Colors.primaries.length],),title:Text('Item $itemNo',key:Key('favorites_text_$itemNo'),),trailing:IconButton(key:Key('remove_icon_$itemNo'),icon:constIcon(Icons.close),onPressed:(){Provider.of<Favorites>(context,listen:false).remove(itemNo);ScaffoldMessenger.of(context).showSnackBar(constSnackBar(content:Text('Removed from favorites.'),duration:Duration(seconds:1),),);},),),);}}

    Add the Home page inlib/screens/home.dart

    a3c16fc17be25f6c.pngIn thelib/screens directory create another new file namedhome.dart. Inlib/screens/home.dart add the following code:

    lib/screens/home.dart

    import'package:flutter/material.dart';import'package:go_router/go_router.dart';import'package:provider/provider.dart';import'../models/favorites.dart';import'favorites.dart';classHomePageextendsStatelessWidget{staticStringrouteName='/';constHomePage({super.key});@overrideWidgetbuild(BuildContextcontext){returnScaffold(appBar:AppBar(title:constText('Testing Sample'),actions: <Widget>[TextButton.icon(onPressed:(){context.go('/${FavoritesPage.routeName}');},icon:constIcon(Icons.favorite_border),label:constText('Favorites'),),],),body:ListView.builder(itemCount:100,cacheExtent:20.0,padding:constEdgeInsets.symmetric(vertical:16),itemBuilder:(context,index)=>ItemTile(index),),);}}classItemTileextendsStatelessWidget{finalintitemNo;constItemTile(this.itemNo,{super.key});@overrideWidgetbuild(BuildContextcontext){varfavoritesList=Provider.of<Favorites>(context);returnPadding(padding:constEdgeInsets.all(8.0),child:ListTile(leading:CircleAvatar(backgroundColor:Colors.primaries[itemNo%Colors.primaries.length],),title:Text('Item $itemNo',key:Key('text_$itemNo'),),trailing:IconButton(key:Key('icon_$itemNo'),icon:favoritesList.items.contains(itemNo)?constIcon(Icons.favorite):constIcon(Icons.favorite_border),onPressed:(){!favoritesList.items.contains(itemNo)?favoritesList.add(itemNo):favoritesList.remove(itemNo);ScaffoldMessenger.of(context).showSnackBar(SnackBar(content:Text(favoritesList.items.contains(itemNo)?'Added to favorites.':'Removed from favorites.'),duration:constDuration(seconds:1),),);},),),);}}

    Replace the contents oflib/main.dart

    a3c16fc17be25f6c.pngReplace the contents oflib/main.dart with the following code:

    lib/main.dart

    import'package:flutter/material.dart';import'package:go_router/go_router.dart';import'package:provider/provider.dart';import'models/favorites.dart';import'screens/favorites.dart';import'screens/home.dart';voidmain(){runApp(constTestingApp());}final_router=GoRouter(routes:[GoRoute(path:HomePage.routeName,builder:(context,state){returnconstHomePage();},routes:[GoRoute(path:FavoritesPage.routeName,builder:(context,state){returnconstFavoritesPage();},),],),],);classTestingAppextendsStatelessWidget{constTestingApp({super.key});@overrideWidgetbuild(BuildContextcontext){returnChangeNotifierProvider<Favorites>(create:(context)=>Favorites(),child:MaterialApp.router(title:'Testing Sample',theme:ThemeData(colorScheme:ColorScheme.fromSeed(seedColor:Colors.deepPurple,),useMaterial3:true,),routerConfig:_router,),);}}

    The app is now complete, but untested.

    a3c16fc17be25f6c.pngRun the app. It should look like the following screenshot:

    b74f843e42a28b0f.png

    The app shows a list of items. Tap the heart-shaped icon on any row to fill in the heart and add the item to the favorites list. TheFavorites button on theAppBar takes you to a second screen containing the favorites list.

    The app is now ready for testing. You'll start testing the app in the next step.

    5. Unit testing the provider

    You'll start by unit testing thefavorites model. What is a unit test? A unit test verifies that every individualunit of software, be it a function, object or a widget, performs its intended task correctly.

    All the test files in a Flutter app, except for integration tests, are placed in thetest directory.

    Note: These instructions use the command line to run the tests. However, you can also use the options provided by VS Code and Android Studio for running unit and widget tests on your application.

    Removetest/widget_test.dart

    a3c16fc17be25f6c.pngBefore you begin testing, delete thewidget_test.dart file. You'll be adding your own test files.

    Create a new test file

    First, you'll test theadd() method in theFavorites model to verify that a new item gets added to the list, and that the list reflects the change. By convention, the directory structure in thetest directory mimics that in thelib directory and the Dart files have the same name with_test appended.

    a3c16fc17be25f6c.pngCreate amodels directory in thetest directory. In this new directory, create afavorites_test.dart file with the following content:

    test/models/favorites_test.dart

    import'package:test/test.dart';import'package:testing_app/models/favorites.dart';voidmain(){group('Testing App Provider',(){varfavorites=Favorites();test('A new item should be added',(){varnumber=35;favorites.add(number);expect(favorites.items.contains(number),true);});});}

    The Flutter testing framework allows you to bind similar tests related to each other in a group. There can be multiple groups in a single test file intended to test different parts of the corresponding file in thelib directory.

    Thetest() method takes two positional parameters: thedescription of the test and thecallback where you actually write the test.

    a3c16fc17be25f6c.pngTest removing an item from the list. Insert the following test in the sameTesting App Provider group:

    test/models/favorites_test.dart

    test('An item should be removed',(){varnumber=45;favorites.add(number);expect(favorites.items.contains(number),true);favorites.remove(number);expect(favorites.items.contains(number),false);});

    Run the test

    a3c16fc17be25f6c.pngAt the command line, navigate to the project's root directory and enter the following command:

    $fluttertesttest/models/favorites_test.dart

    If everything works, you should see a message similar to the following:

    00:06+2:Alltestspassed!

    The complete test file:test/models/favorites_test.dart.

    Tip: You can run all the tests in thetest directory at once by running:

    $ flutter test

    For more information on unit testing, visitAn introduction to unit testing.

    6. Widget testing

    In this step you'll add code to test widgets. Widget testing is unique to Flutter, where you can test each widget in an isolated fashion. This step tests theHomePage andFavoritesPage screens individually.

    Widget testing uses thetestWidget() function instead of thetest() function. Like thetest() function, thetestWidget() function takes two parameters:description, andcallback, however the callback takes aWidgetTester as its argument.

    Widget tests useTestFlutterWidgetsBinding, a class that provides the same resources to your widgets that they would have in a running app, e.g. information about screen size, the ability to schedule animations, but without running inside an app. Instead, a virtual environment is used to instantiate the widget, and then run tests the results. Here,pumpWidget kicks off the process by telling the framework to mount and measure a particular widget just as it would in an application.

    The widget testing framework provides finders to find widgets, for exampletext(),byType(), andbyIcon(). The framework also provides matchers to verify the results.

    Start by testing theHomePage widget.

    Create a new test file

    The first test verifies whether scrolling theHomePage works properly.

    a3c16fc17be25f6c.pngCreate a new file in thetest directory and name ithome_test.dart. In the newly created file, add the following code:

    test/home_test.dart

    import'package:flutter/material.dart';import'package:flutter_test/flutter_test.dart';import'package:provider/provider.dart';import'package:testing_app/models/favorites.dart';import'package:testing_app/screens/home.dart';WidgetcreateHomeScreen()=>ChangeNotifierProvider<Favorites>(create:(context)=>Favorites(),child:constMaterialApp(home:HomePage(),),);voidmain(){group('Home Page Widget Tests',(){testWidgets('Testing Scrolling',(tester)async{awaittester.pumpWidget(createHomeScreen());expect(find.text('Item 0'),findsOneWidget);awaittester.fling(find.byType(ListView),constOffset(0,-200),3000,);awaittester.pumpAndSettle();expect(find.text('Item 0'),findsNothing);});});}

    ThecreateHomeScreen() function is used to create an app that loads the widget to be tested in a MaterialApp, wrapped into a ChangeNotifierProvider. The HomePage widget needs both of these widgets to be present above it in the widget tree so it can inherit from them and get access to the data they offer. This function is passed as a parameter to thepumpWidget() function.

    Next, test whether the framework can find aListView rendered onto the screen.

    Note: This test is supposed to be run before the scrolling test as you are performing actions on theListView in it. However, to give you a general idea of how widgets tests are written we wrote the scrolling test first.

    a3c16fc17be25f6c.pngAdd the following code snippet tohome_test.dart:

    test/home_test.dart

    group('Home Page Widget Tests',(){//BEGINNINGOFNEWCONTENTtestWidgets('Testing if ListView shows up',(tester)async{awaittester.pumpWidget(createHomeScreen());expect(find.byType(ListView),findsOneWidget);});//ENDOFNEWCONTENTtestWidgets('Testing Scrolling',(tester)async{awaittester.pumpWidget(createHomeScreen());expect(find.text('Item 0'),findsOneWidget);awaittester.fling(find.byType(ListView),constOffset(0,-200),3000,);awaittester.pumpAndSettle();expect(find.text('Item 0'),findsNothing);});});

    Run the test

    First, run the test in the same way you would run a unit test, with the command:

    $fluttertesttest/home_test.dart

    The test should run quickly, and you should see a message like this one:

    00:02+2:Alltestspassed!

    You can also run widget tests using a device or an emulator, which allows you to watch the test running. It also gives you the ability to use hot restart.

    a3c16fc17be25f6c.pngPlug-in your device or start your emulator. You can also run the test as a desktop application.

    a3c16fc17be25f6c.pngFrom the command line, navigate to the project's root directory and enter the following command:

    $flutterruntest/home_test.dart

    You may need to select the device to run the test on. In that case, follow the instructions and select a device:

    Multiple devices found:Linux (desktop) • linux  • linux-x64      • Ubuntu 22.04.1 LTS 5.15.0-58-genericChrome (web)    • chrome • web-javascript • Google Chrome 109.0.5414.119[1]: Linux (linux)[2]: Chrome (chrome)Please choose one (To quit, press "q/Q"):

    If everything works you should see an output similar to the following:

    Launchingtest/home_test.dartonLinuxindebugmode...BuildingLinuxapplication...flutter:00:00+0:HomePageWidgetTestsTestingifListViewshowsupSyncingfilestodeviceLinux...62msFlutterrunkeycommands.rHotreload.🔥🔥🔥RHotrestart.hListallavailableinteractivecommands.dDetach(terminate"flutter run"butleaveapplicationrunning).cClearthescreenqQuit(terminatetheapplicationonthedevice).💪Runningwithsoundnullsafety💪AnObservatorydebuggerandprofileronLinuxisavailableat:http://127.0.0.1:35583/GCpdLBqf2UI=/flutter:00:00+1:HomePageWidgetTestsTestingScrollingTheFlutterDevToolsdebuggerandprofileronLinuxisavailableat:http://127.0.0.1:9100?uri=http://127.0.0.1:35583/GCpdLBqf2UI=/flutter:00:02+2:Alltestspassed!

    Next, you'll make changes to the test file and pressShift + R to hot restart the app and re-run all the tests. Do not stop the application.

    a3c16fc17be25f6c.pngAdd more tests to the group that tests the HomePage widgets. Copy the following test to your file:

    test/home_test.dart

    testWidgets('Testing IconButtons',(tester)async{awaittester.pumpWidget(createHomeScreen());expect(find.byIcon(Icons.favorite),findsNothing);awaittester.tap(find.byIcon(Icons.favorite_border).first);awaittester.pumpAndSettle(constDuration(seconds:1));expect(find.text('Added to favorites.'),findsOneWidget);expect(find.byIcon(Icons.favorite),findsWidgets);awaittester.tap(find.byIcon(Icons.favorite).first);awaittester.pumpAndSettle(constDuration(seconds:1));expect(find.text('Removed from favorites.'),findsOneWidget);expect(find.byIcon(Icons.favorite),findsNothing);});

    This test verifies that tapping theIconButton changes fromIcons.favorite_border (an open heart) toIcons.favorite (a filled-in heart) and then back toIcons.favorite_border when tapped again.

    a3c16fc17be25f6c.pngEnterShift + R. This hot restarts the app and re-runs all the tests.

    The complete test file:test/home_test.dart.

    a3c16fc17be25f6c.pngUse the same process to test theFavoritesPage with the following code. Follow the same steps and run it.

    test/favorites_test.dart

    import'package:flutter/material.dart';import'package:flutter_test/flutter_test.dart';import'package:provider/provider.dart';import'package:testing_app/models/favorites.dart';import'package:testing_app/screens/favorites.dart';lateFavoritesfavoritesList;WidgetcreateFavoritesScreen()=>ChangeNotifierProvider<Favorites>(create:(context){favoritesList=Favorites();returnfavoritesList;},child:constMaterialApp(home:FavoritesPage(),),);voidaddItems(){for(vari=0;i <10;i+=2){favoritesList.add(i);}}voidmain(){group('Favorites Page Widget Tests',(){testWidgets('Test if ListView shows up',(tester)async{awaittester.pumpWidget(createFavoritesScreen());addItems();awaittester.pumpAndSettle();expect(find.byType(ListView),findsOneWidget);});testWidgets('Testing Remove Button',(tester)async{awaittester.pumpWidget(createFavoritesScreen());addItems();awaittester.pumpAndSettle();vartotalItems=tester.widgetList(find.byIcon(Icons.close)).length;awaittester.tap(find.byIcon(Icons.close).first);awaittester.pumpAndSettle();expect(tester.widgetList(find.byIcon(Icons.close)).length,lessThan(totalItems));expect(find.text('Removed from favorites.'),findsOneWidget);});});}

    This test verifies whether an item disappears when the close (remove) button is pressed.

    For more information on widget testing, visit:

    7. Testing app UI with integration tests

    Integration tests are used to test how the individual pieces of an app work together as a whole. Theintegration_test library is used to perform integration tests in Flutter. This is Flutter's version of Selenium WebDriver, Protractor, Espresso, or Earl Gray. The package usesflutter_driver internally to drive the test on a device.

    Writing integration tests in Flutter is similar to writing widget tests, with the exception that integration tests run on a mobile device, browser, or desktop application, called the target device.

    Write the test

    a3c16fc17be25f6c.pngCreate a directory calledintegration_test in the project's root directory, and in that directory create a new file namedapp_test.dart.

    integration_test/app_test.dart

    import'package:flutter/material.dart';import'package:flutter_test/flutter_test.dart';import'package:testing_app/main.dart';voidmain(){group('Testing App',(){testWidgets('Favorites operations test',(tester)async{awaittester.pumpWidget(constTestingApp());finaliconKeys=['icon_0','icon_1','icon_2',];for(variconiniconKeys){awaittester.tap(find.byKey(ValueKey(icon)));awaittester.pumpAndSettle(constDuration(seconds:1));expect(find.text('Added to favorites.'),findsOneWidget);}awaittester.tap(find.text('Favorites'));awaittester.pumpAndSettle();finalremoveIconKeys=['remove_icon_0','remove_icon_1','remove_icon_2',];for(finaliconKeyinremoveIconKeys){awaittester.tap(find.byKey(ValueKey(iconKey)));awaittester.pumpAndSettle(constDuration(seconds:1));expect(find.text('Removed from favorites.'),findsOneWidget);}});});}

    Run the test

    a3c16fc17be25f6c.pngPlug-in your device or start your emulator. You can also run the test as a desktop application.

    a3c16fc17be25f6c.pngAt the command line, navigate to the project's root directory and enter the following command:

    $fluttertestintegration_test/app_test.dart

    If everything works, you should see an output similar to the following:

    Multipledevicesfound:Linux(desktop)linuxlinux-x64Ubuntu22.04.1LTS5.15.0-58-genericChrome(web)chromeweb-javascriptGoogleChrome109.0.5414.119[1]:Linux(linux)[2]:Chrome(chrome)Pleasechooseone(Toquit,press"q/Q"):100:00+0:loading/home/miquel/tmp/testing_app/integration_test/app_test.dartB00:08+0:loading/home/miquel/tmp/testing_app/integration_test/app_test.dart00:26+1:Alltestspassed!

    Note: Running integration tests on Chrome requires a different setup, which can be found in theintegration testing documentation.

    8. Testing app performance with Flutter Driver

    Write a performance test

    Create a new test file named perf_test.dart in the integration_test folder with the following content:

    integration_test/perf_test.dart

    import'package:flutter/material.dart';import'package:flutter_test/flutter_test.dart';import'package:integration_test/integration_test.dart';import'package:testing_app/main.dart';voidmain(){group('Testing App Performance',(){finalbinding=IntegrationTestWidgetsFlutterBinding.ensureInitialized();binding.framePolicy=LiveTestWidgetsFlutterBindingFramePolicy.fullyLive;testWidgets('Scrolling test',(tester)async{awaittester.pumpWidget(constTestingApp());finallistFinder=find.byType(ListView);awaitbinding.traceAction(()async{awaittester.fling(listFinder,constOffset(0,-500),10000);awaittester.pumpAndSettle();awaittester.fling(listFinder,constOffset(0,500),10000);awaittester.pumpAndSettle();},reportKey:'scrolling_summary');});});}

    TheensureInitialized() function verifies if the integration test driver is initialized, reinitializing it if required. SettingframePolicy tofullyLive is good for testing animated code.

    This test scrolls through the list of items really fast and then scrolls all the way up. ThetraceAction() function records the actions and generates a timeline summary.

    Capture the performance results

    To capture the results, create a folder namedtest_driver with a file namedperf_driver.dart, and add the following code:

    test_driver/perf_driver.dart

    import'package:flutter_driver/flutter_driver.dart'asdriver;import'package:integration_test/integration_test_driver.dart';Future<void>main(){returnintegrationDriver(responseDataCallback:(data)async{if(data!=null){finaltimeline=driver.Timeline.fromJson(data['scrolling_summary']asMap<String,dynamic>);finalsummary=driver.TimelineSummary.summarize(timeline);awaitsummary.writeTimelineToFile('scrolling_summary',pretty:true,includeSummary:true,);}},);}

    Run the test

    a3c16fc17be25f6c.pngPlug-in your device or start your emulator.

    a3c16fc17be25f6c.pngAt the command line, navigate to the project's root directory and enter the following command:

    $flutterdrive\--driver=test_driver/perf_driver.dart\--target=integration_test/perf_test.dart\--profile\--no-dds

    If everything works, you should see an output similar to the following:

    Running "flutter pub get" in testing_app...Resolving dependencies...   archive 3.3.2 (3.3.6 available)  collection 1.17.0 (1.17.1 available)  js 0.6.5 (0.6.7 available)  matcher 0.12.13 (0.12.14 available)  meta 1.8.0 (1.9.0 available)  path 1.8.2 (1.8.3 available)  test 1.22.0 (1.23.0 available)  test_api 0.4.16 (0.4.18 available)  test_core 0.4.20 (0.4.23 available)  vm_service 9.4.0 (11.0.1 available)  webdriver 3.0.1 (3.0.2 available)Got dependencies!Running Gradle task 'assembleProfile'...                         1,379ms✓  Built build/app/outputs/flutter-apk/app-profile.apk (14.9MB).Installing build/app/outputs/flutter-apk/app-profile.apk...        222msI/flutter ( 6125): 00:04 +1: Testing App Performance (tearDownAll)I/flutter ( 6125): 00:04 +2: All tests passed!All tests passed.

    After the test completes successfully, the build directory at the root of the project contains two files:

    1. scrolling_summary.timeline_summary.json contains the summary. Open the file with any text editor to review the information contained within.
    2. scrolling_summary.timeline.json contains the complete timeline data.

    For more details on integration testing, visit:

    9. Congratulations!

    You've completed the codelab and have learned different ways to test a Flutter app.

    What you've learned

    • How to test providers with the help of unit tests
    • How to test widgets using the widget testing framework
    • How to test the app's UI using integration tests
    • How to test the app's performance using integration tests

    To learn more about testing in Flutter, visit

    Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.