Debugging, Troubleshooting, and Performance Considerations
Debugging, Troubleshooting, and Performance Considerations
In this chapter, we are going to focus on the debugging, testing, and iterating portions of the cycle, with a focus on learning what to do when our code goes wrong and improving the overall responsiveness of our applications.
Example 11.1–Example 11.3 in the Chapter 11 folder; each code block below is labelled with its example number. Blocks without a label have no counterpart in the repository. The repository has conversion glitches of its own, so the code on this page follows the book (BPB Publications, n.d.).Chapter overview
Structure
- Debugging and troubleshooting concepts
- Logging output to the debug console
- Setting breakpoints and exploring runtime variables
- Handling exceptions
- Introduction to Flutter DevTools
- Defining performance issues
- Exploring profile mode
- When a ListView is not a ListView
- Optimizing widgets
Objectives
Runnable example
examples/flutter_for_jobseekers_ch11/. The code on this page is shown as the book prints it, with conversion glitches fixed.Debugging and troubleshooting concepts
Even the most seasoned developers spend a lot of time debugging and troubleshooting their code. It is a rare occurrence when your code works flawlessly the first time, so learning how to solve the problems you will come across is very important. Let us first start by defining what debugging and troubleshooting are.
Troubleshooting
Debugging
Every problem to be solved by debugging can be broken down into five steps:
Reproduce it
Ensure the error is reproduceable. If the error is intermittent, you have not properly identified the error.
Confirm it is the right problem
Be certain that the problem you are debugging is the problem you need to be solving.
Check the obvious
Check all the obvious error sources. It is easy to waste time by debugging a complex problem that turns out to have a very simple and obvious solution.
Debug the problem
Isolate the problem by dividing it into working versus non-working components. Think like a computer: step through the instructions one at a time to find where the operation fails.
Reassess
If you are unable to identify the root cause of the problem, reassess the situation: what assumptions have you made that might be incorrect? Walk through the process again, taking notes and using knowledge learned from the last time.
Although these steps are seemingly quite simple, building the mindset and toolkit to approach and debug any problem takes time and practice. In each section of this chapter, we will discuss some of the different tools you can employ to help debug your Flutter project.
Logging output to the debug console
Sometimes it is useful to print some messages to the console while we debug a problem. Let us look at some pseudo-code (a code-like representation, often non-functional, which is used to illustrate a solution or mock out a problem):
Future<MyObject?> getMyObject() async {
Map<String, dynamic> result = await getResult();
MyObject object = MyObject.fromJson(result);
if (object.name.isEmpty) {
return null;
}
return object;
}
Our code will await a future result, build an object from it, check if the object's name property is null, and either returns a null object or the full object, respectively. What you might find is a situation in which this method always returns null, even when you are certain the object has a name.
object.name.isEmpty), not whether it is null; name is a non-nullable String here.The first and most obvious thing to do would be to ask Flutter to print out the name of the object, but how and where should we do that? First, we will need to import the dart:developer package to gain access to the log() method.
dart:math package, log() will already be defined as a method! In that case, do not fret, as you can use import 'dart:developer' as dev; to scope the package to a namespace. Then, use dev.log() to access the function.dart:developer and dart:math are not packages but Dart core libraries; you import them with import 'dart:developer'; and add nothing to pubspec.yaml (see the same note on dart:io in Chapter 10).Do not worry about following along in your editor, since we have not defined MyObject or getResult(). Instead, use this as a thought experiment:
import 'dart:developer';
Future<MyObject?> getMyObject() async {
Map<String, dynamic> result = await getResult();
MyObject object = MyObject.fromJson(result);
log("The object's name is '${object.name}'");
if (object.name.isEmpty) {
return null;
}
return object;
}
On Line 7, we have our log message. The rules for accessing variables in a log message are the same as printing them in a string: use a dollar sign to denote the variable and wrap the variable in curly braces if you need to access a property of the variable.
Now, imagine we ran the code again and checked the log message. Unfortunately, the log message never shows up. What is going on here? Let us add some more logging to see if we can figure out where things are breaking:
import 'dart:developer';
Future<MyObject?> getMyObject() async {
log('About to run getResult()');
Map<String, dynamic> result = await getResult();
log('The result is $result. Using it to create MyObject.');
MyObject object = MyObject.fromJson(result);
log('MyObject was created: $object');
log("The object's name is '${object.name}'");
if (object.name.isEmpty) {
return null;
}
return object;
}
Runnable copy: examples/flutter_for_jobseekers_ch11/lib/debugging/logging.dart (with an assembled MyObject in lib/debugging/my_object.dart, whose fromJson throws for an empty map)
Now if we run the code, here is what we might see:
[log] About to run getResult()
[log] The result is {}. Using it to create MyObject.
It looks like we have isolated the problem using logging. Something about the getResult() method does not seem to be working. We will have to continue the troubleshooting with a different method, so let us head over to that method and figure out what is going on.
Setting breakpoints and exploring runtime variables
There are quicker and easier ways to debug than by inserting logging lines everywhere. Since you are unlikely to want to keep those lines in your code when you ship it, you will likely go back and delete them once you have fixed the problem. One way we can sidestep the whole process of writing and deleting code is by leveraging the tools of our Integrated Development Environment (IDE). In this case, our IDE is Visual Studio Code. Any decent and/or modern IDE will have similar functionality. While the details of how to use the tool changes from IDE to IDE, the concept is usually the same.
Let us take our code from before and add a breakpoint (Figure 11.1). Once the breakpoint has been set, you will see a red dot next to the line number, indicating a breakpoint exists for that line of code. If the dot is grey instead of red, you will need to stop and restart your code. You will also see the breakpoint is added to the IDE's breakpoints list, including the filename and path of the file with a breakpoint, along with the line number.

Figure 11.1: Setting a breakpoint in Visual Studio Code
Running our code with one or more breakpoints set will cause the program to pause once it hits the line(s) with the breakpoint(s). Once a line with a breakpoint has been reached, the debugger in the IDE will present us with some useful information. The current line that was being processed when a breakpoint was reached, will be highlighted. Additionally, the call stack will be populated with information about what code is currently being processed at the time the breakpoint has been reached. Each line (called a stack frame) shows what function was running when the previous line was invoked. Refer to Figure 11.2 for a visual of what happens when you reach a breakpoint.

Figure 11.2: A breakpoint has been reached.
The debugger toolbar
You may have noticed when running your code before that there are several little arrows in the same bar where you can stop or restart your code. Typically, the first icon would be a pause icon (
); however, when the debug point is reached, it changes to a resume icon (
). Let us talk about what each of the blue icons does, starting with the pause/resume icon.
Pause / Resume
Step over
Step into
Step out
The next three icons (step over, step into and step out) are only available while code execution has been paused.
By using the step into and step out buttons, we can process the lines of code one-by-one until we come to the root of our problem. In Figure 11.3, we see that the getResult method only returns an object with a name if the future is not false.

Figure 11.3: Using the step into and step out buttons, we can identify which line of code causes our problem.
Let us examine this code more closely:
Future<Map<String, dynamic>> getResult() async {
bool? future = await Future.delayed(
const Duration(seconds: 5),
).timeout(
const Duration(seconds: 1),
onTimeout: () {
return false;
},
);
if (future != false) return {'name': 'my object'};
return {};
}
Runnable copy: examples/flutter_for_jobseekers_ch11/lib/debugging/logging.dart
Here, we can see that the debugger tells us future is equal to false. Looking at the line of code which checks the value of the future, we confirm that a valid object will only be returned if future is equal to anything other than false. Looking at the preceding lines, we see that the future waits several seconds, but times out before it completes. When it times out, false is returned. By using the debugging tools, we have isolated the area of code where the problem exists.
You can read more about Visual Studio Code's debugger on their website, https://code.visualstudio.com/docs/editor/debugging.
Handling exceptions
An exception occurs when something has gone wrong in our code and processing is unable to continue; otherwise, the program will crash. We can tell our code to throw exceptions when processing goes wrong, such as in this updated example from before:
Future<Map<String, dynamic>> getResult() async {
await Future.delayed(
const Duration(seconds: 5),
).timeout(
const Duration(seconds: 1),
onTimeout: () {
throw Exception('Operation timed out.');
},
);
return {'name': 'my object'};
}
Here, instead of setting the future to a boolean value, we assume it will complete successfully and do not even bother checking the condition before returning a value from the function. Instead, we tell the future to throw an exception if the code times out. See Figure 11.4 for how it looks when this happens:

Figure 11.4: An exception has been thrown.
Now that we have an exception, we need to learn how to deal with them. One way we can deal with exceptions in our code is by using a try/catch block. The code within the try portion will run until an exception is thrown. In the case an exception is thrown, the code within the catch portion will run. Otherwise, the catch code will be skipped. In this example, we have wrapped the function call in a try/catch block:
Future<MyObject?> getMyObject() async {
late Map<String, dynamic> result;
try {
result = await getResult();
} catch (e) {
log('An exception occurred while running `getResult`: $e');
return null;
}
MyObject object = MyObject.fromJson(result);
if (object.name.isEmpty) {
return null;
}
return object;
}
Runnable copy: examples/flutter_for_jobseekers_ch11/lib/debugging/exceptions.dart
Now, when we run our code, a log message is produced, but the exception does not stop the rest of our code from running (Figure 11.5):

Figure 11.5: The exception has been handled, allowing our code to continue running.
try/catch can obfuscate problems entirely, leading to frustration while debugging. In this case, we included a log message which logs the actual exception. If we had not done that, we would have no idea that an exception occurred. For this reason, you should consider using try/catch blocks sparingly. Instead, writing more robust code should prevent many exceptions from happening in the first place, being sure to run appropriate checks on variables throughout the process and handling any error states that could occur.Introduction to Flutter's DevTools
Outside of your IDE's debugger, Flutter comes with a robust set of tools called DevTools. DevTools comes with many different components, from a visual widget tree, layout explorer, and widget details tree to tools that help you visualize when a widget is rebuilt, a network inspector, and the ability to tap on any widget to jump straight to it in the code and within DevTools. By default, opening the DevTools by pressing the icon (
) in the toolbar will drop you into the Widget Inspector, side-by-side with your code. See Figure 11.6 for an example of the DevTools, after having been moved to its own tab:

Figure 11.6: Flutter's DevTools
The Widget Inspector
There are far too many tools available in DevTools for us to cover here, so let us look at some of the most common tools, starting with the layout explorer. Selecting a widget from the widget tree will jump to the code where that widget is defined in the editor tab, then display information about the widget in the layout explorer. The layout explorer will give information about the RenderBox that your selected widget is contained within, as well as information about the constraints and sizing. If your widget is of a Flexible type, such as a Row or Column, you will also be able to temporarily change the flex property to instantly see the changes in your app, all without having to write code.
Row and Column are Flex widgets (both extend Flex in the Flutter SDK), not Flexible ones. Flexible (and its subclass Expanded) is the widget you wrap a child of a Row or Column in, and its flex property is the one you can change (flutter/flutter, n.d.).Many applications will not have such a simple layout where it is quick and easy to find the exact widget you are looking for in the widget tree. If you have a particularly complex layout, you can search for a widget using the magnifying glass icon in the widget tree header (see Figure 11.7). Using the search, you can search by things such as the widget type and properties:

Figure 11.7: Searching for a Widget
Another useful tool to find widgets in your widget tree is the Select widget mode. Located to the top-left of the Widget Inspector panel is a button with a mouse cursor and, depending on the size of your window, a text label. Clicking this button will the ability for you to click or tap on any widget from directly within your application to focus on it in the layout explorer and widget tree, as well as within the code itself.
Once you have selected a widget in DevTools, additional details can be found in two tabs:
Layout Explorer
Row or Column, additional information about the widget's flex, fit, and alignment is available. Each of these values can be manipulated in DevTools to see how a corresponding change in the code would impact the application's layout, in real-time.Widget Details Tree
These tools are invaluable when tracking down issues in your application, as they help to shed light on precisely how the widget is composed.
The DevTools Widget Inspector also includes a host of other useful tools. The button toggles for each of these tools resides at the top of the Widget Inspector pane:
- options to slow down animations,
- highlight widgets each time they repaint,
- display an overlay consisting of widget boundaries and other layout information,
- an option to show text baselines (to ensure text is aligned properly across widgets),
- and to highlight images which are oversized and using too much memory.
Opening the other DevTools panels
Flutter's DevTools are not limited to inspecting widgets. Although not immediately obvious at first, there are several other panes of useful tools.
Hover over the language status
Hover your cursor over the Editor Language Status field (which looks like {}) at the bottom-left of Visual Studio Code, in the status bar. If the status item is not present, first check that your editor is focused on a Dart file (rather than, say, the Widget Inspector), and if all else fails, right click the status bar to ensure the Editor Language Status option is checked.
Launch Dart DevTools
On the line which says Dart DevTools, click the Launch link.
Choose a panel
A popup will appear asking you which part of DevTools you would like to open. See Figure 11.8 for a visual reference.

Figure 11.8: The process of launching different parts of DevTools requires you to hover over an item in the status bar then click launch before choosing which panel to open
The various panels available to us are the Widget Inspector, which we have already discussed at length; the CPU Profiler, Memory, and Performance panels, which we will look at later in this chapter; the Network panel, Logging panel; and the option to launch DevTools in your Web browser. Let us look at the Logging and Network panels.
The Logging panel
The Logging panel (see Figure 11.9) includes a timeline of messages logged by your code and the Flutter framework throughout the lifecycle of your application. Each line in the timeline can be clicked to view the contents of the message. When using the dart:developer package, the print() function, or the debugPrint() function to log messages, you can find the output in the Logging panel. This is especially useful if your debug console is flooded with output while your app runs, as you can easily find the logged message by using the search feature or scrolling through the list. Take note that the print() and debugPrint() functions write to the standard output and will therefore be labelled with the kind stdout.
print() and debugPrint() functions will only print the first 12,288 characters in a message. This can be especially frustrating if you are trying to log a large JSON response from an API, for example. If you find yourself frequently logging large pieces of data and not being able to see all of it in the Logging panel, switch to the log() function and your woes will soon be gone.12 * 1024, the _kDebugPrintCapacity of debugPrint's default implementation, debugPrintThrottled. It is not a cut-off: once that many characters have been printed, debugPrint pauses for a second and then prints the remaining lines, "to avoid data loss on Android" (flutter/flutter, n.d.). Plain print() does not go through this throttle. The 12,288 figure therefore says nothing about lost output; it only means that long debugPrint output can arrive with a delay, and out of order with print() calls.
Figure 11.9: The logging tool, part of Flutter's DevTools
The Network panel
Now, let us look at the Network panel (Figure 11.10). This is where you can find some (but not all — more on that in a minute) network requests made by your application. You will find information about the location of the request (often, the URL), the method of the request (whether it is a GET, PUT, POST, and so on), the status, port number, content type, number of bytes read and written, and other useful information which can be used to gain insight into network connections. If you were to make a request to an API, for example, you could find the API's response in the detailed view on the Network panel.

Figure 11.10: The Network panel of Flutter's DevTools showing some activity
HttpClient are visible (see the bug being tracked for this issue at https://github.com/flutter/devtools/issues/4829). There also appears to be an issue when developing in certain environments, such as within a Hyper-V Virtual Machine (see the bug filed here: https://github.com/flutter/devtools/issues/4997), but this should impact relatively few people. Still, it may be something worth considering if you are developing in such an environment.Given the limitations of the Network panel in Flutter's DevTools, it may be wise to trust but verify when it comes to the data presented in it. If the network requests are present, you can be assured that they are valid and correct. However, for the time being, do not trust that all network requests will be present here. Until the team has had more time to flesh out this component of the DevTools, you may want to find other ways to inspect the network traffic of your application, if possible.
cupertino_http, cronet_http and ok_http packages report their requests to DevTools through the http_profile package (flutter/devtools, 2025a). Flutter's Network view documentation now says that all traffic from dart:io (such as HttpClient, including the dio package) is logged, as is traffic logged with http_profile (Flutter, n.d.-c). #4997 (Hyper-V) was closed as not reproducible on 2025-07-07 (flutter/devtools, 2025b).Defining performance issues
Before we dive into what tools Flutter gives us to analyze the performance of our applications, we should define a few key terms and ideas. First, it is relevant to reiterate the fact that Flutter was always designed to be 60 frames-per-second (fps) from the very start, and each release of Flutter and the underlying Dart programming language often finds new ways to increase performance without requiring changes to your code. Flutter is very good at rendering large numbers of widgets on the screen, even animating them every frame without slowdowns.
The performance of an application can be broadly split into two categories:
Space
Time
Frames and vsync
Every device with a display will update that display at a fixed (or sometimes variable) refresh rate. For many devices these days, that is 60fps (which happens to be the target framerate of Flutter.) However, newer displays are capable of 100, 120, or even 240+ fps. That means the contents of the display are redrawn every 1/x seconds. For a 60fps display, the contents are redrawn every 1/60th of a second.
Ok, but how does this relate to performance? Simply put, this means Flutter has 1/60th of a second to build and lay out all the widgets on the screen (called a frame) before the next screen refresh interval, called the vsync. Vsync is used to synchronize the refresh rate and the frame rate of the monitor to prevent tearing or when the screen displays information from multiple frames in a single screen draw. Tearing appears as a horizontal line across the screen where the image being displayed is split across one or more parts of the image. If a frame fails to build within vsync period, it will not be rendered until it is completed building.
Jank
Consider a spinning widget, rotating smoothly at 60fps. Suddenly, the widget appears to stop rotating, then a couple of frames later, snaps into the position it would have been in had it continued rotating smoothly. This phenomenon is called jank.
vsync period to build. If the frame has not been built yet, it cannot be displayed.In the following illustration (Figure 11.11), the vsync period is marked by the dashed line, whereas the frame build time is denoted by rectangles:

Figure 11.11: A visual representation of jank
However, even if you manage to avoid jank by ensuring your frames are built within the vsync period, you are not completely out of the water yet. If your frames take the entire vsync period to build, your app will consume a lot more energy. This will lead to shorter battery life on mobile devices, and generally contributes to global warming. We ought to strive to avoid this scenario. Figure 11.12 represents what it might look like if we do not have jank but are taking too long to build our frames:

Figure 11.12: When a frame takes too long to build but still finishes within the vsync period, it will consume more energy.
So, if we can see that there is jank in our app, how do we verify it and identify the widget(s) causing the problem? Likewise, how do we identify whether our app is using too much memory and fix it? To do that, we will need to explore profile mode.
Exploring profile mode
Flutter can build your application in three different modes: debug mode, profile mode, and release mode (Figure 11.13). Up to this point, we have been focused on debug mode, as it is the default for development and the most common mode you will be using while writing applications.

Figure 11.13: Flutter's three modes of building an application
To run your application in profile mode, either choose the profile mode option from the dropdown in Visual Studio Code, or use the following command:
flutter run --profile
The Performance panel
Once you are in profile mode, go ahead and open the Performance panel by pressing the leftmost button in the toolbar, next to the stop button (Figure 11.14):

Figure 11.14: The Performance panel in Flutter's DevTools is available only when running in profile mode
On the top of this panel is a graph, where the X-axis is the frame number, and the Y-axis is a measure of time. The bars are color-coded to correspond to different aspects of the frame compilation process. Bars in orange and red are jank and shader compilation, respectively, and are generally not something we want to see. Additionally, there is a horizontal line in the middle of the graph, marking the point at which a frame needs to be finished to avoid jank. In Figure 11.14, frame 59 comes in just below that line. In Figure 11.15, frames 54 and 56 exceed it:

Figure 11.15: The performance graph
Tapping on a frame will display details in the panel below (Figure 11.16) of what processes comprise a given frame compilation. Tapping on any event in the details view will give you even more details of that event, including precisely how many microseconds it took to run. By exploring the different processes that your widgets run, you can discover what operations are expensive (that is, they take a long time) and either avoid them entirely or use them sparingly.

Figure 11.16: Details of a timeline event
By default, it may be difficult to determine exactly which widget(s) are taking a long time to build. We can remedy this by enabling a more expensive (and thereby slower) option to track widget builds (Figure 11.17). By enabling this option, specific widgets will appear in the timeline event details panel, thereby making it far easier to track precisely which widgets are causing your application to have performance issues.

Figure 11.17: Enabling the option to track widget builds
The performance overlay
Finally, there is a button to the left of the one we just pressed to enable tracking widget builds which will toggle a performance overlay directly on your application (Figure 11.18). This can provide more immediate feedback while using the application to identify which touches, drags, taps, and other actions cause slowdowns and jank. It may be easier to visualize these slowdowns with the performance overlay on the application, so your focus is not divided between interacting with the application and the tools in your IDE.
There are two graphs that will appear:
UI graph (bottom)
Raster graph (top)
ClipRRect widget), shadows, or by using one of Flutter's most expensive operations, SaveLayer.For more information regarding SaveLayer, the documentation found at https://api.flutter.dev/flutter/dart-ui/Canvas/saveLayer.html is an excellent resource.
saveLayer (lowercase s), a method of Canvas; its documentation says that "Generally speaking, saveLayer is relatively expensive" (Flutter, n.d.-d).
Figure 11.18: A performance overlay has been toggled on the running application
The CPU Profiler
Next, we are going to be looking at the CPU Profiler, which will list all the various processes which occur during a recorded timeframe. To launch the CPU Profiler, you will use the same method we used before to launch the network and logging panels.
Record
The CPU Profiler is an expensive process to run, so by default it will be empty. To get started, press the circle Record button at the top.
Interact
Perform one or more actions within your application.
Stop
Press the square Stop button. Depending on how long you recorded for, it could take a while to process the results.
Once the results have been processed, you will see a tree view of each method called by your application, many of which you have not explicitly called yourself, but are called by widgets and methods you have used (see Figure 11.19). Each item is an expandable list, where you can continue to drill down into the subsequent methods that have been called by the previous method. By examining this tree, you will be able to identify the most expensive operations which your application has performed.

Figure 11.19: A sampling recorded by the CPU Profiler
The flame chart can be interpreted as a top-down stack frame, much like the call tree. Rather than having an expandable list, however, the information is presented more visually. This view is an excellent tool for quickly identifying expensive operations, due to the correlation between the length of the bar and the amount of CPU time taken to perform that operation. At a glance, it is easy to pick out widgets and operations which should be investigated for performance improvements.

Figure 11.20: The CPU Flame Chart tab of the CPU Profiler
The Memory tool
Lastly comes the memory tool. This tool can help you to identify which aspects of your application are taking up precious system memory.
Memory (RAM)
Storage
Due to the nature of memory, it is one of the most precious resources on a computing device. Any action you want the CPU to take will require loading information into the RAM before it can be processed. This means that when you want to read a file off the disk and display it on the screen, the contents of the file are loaded into RAM before being processed by the CPU and drawn to the display. Modern computing devices and programming languages have all sorts of tricks up their sleeve to optimize memory utilization, and Flutter is no different in this regard.
If, for example, you want to display a ListView of ListTiles with Text widgets containing an incrementing list of numbers, the list of numbers will need to be stored in memory (as well as everything else Flutter needs to perform the computation and layout.) In Figure 11.21, we have opened the memory tool and found the Paragraph class, where we are able to see that there are 2,000 instances consuming a total of 93.8 KB of memory.

Figure 11.21: The Memory view of DevTools in Profile mode
Due to a bug in DevTools (https://github.com/flutter/devtools/issues/5174), we will need to temporarily switch back to debug mode for the next task. This bug may be resolved by the time you are reading this, so check the status of the bug before switching to debug mode.
Continuing along, if we switch to the Trace tab, we will get a list of all the objects used by the framework to build the screen. We can then track these objects by checking the box(es), interacting with the application, then pressing the Refresh button on the Trace tab, which will then place a dot in the graph when that object is created (Figure 11.22). By selectively choosing potentially memory consuming widgets to track, you can get a sense of how many of these widgets are being created and whether it matches your expectations. More on this in a bit.

Figure 11.22: Tracking Text widget creation
Some of these tools can feel overwhelming to use. There is a lot of information being thrown at you by them, and not all of it will make sense. Thankfully, as we covered at the beginning of this chapter, Flutter does a great job of optimizing layouts right out of the box. The tools listed here are useful when you notice jank, high memory usage by your application, and other unexplained slowdowns. For the most part, unless your task is to explicitly find performance improvements to optimize your application, you likely will not be using these tools very often. However, the fact that they exist and knowing what they do is valuable information in and of itself.
When a ListView is not a ListView
Now that we have explored the various profiling tools available to us, let us put them to use. First, let us consider the section's title: When a ListView is not a ListView. To understand that we must first understand what a ListView is and why you would want to use it.
Using our earlier example of a list of integers, let us say we want to display them in a vertically scrolling list of widgets. First, let us generate a list of integers:
final List<int> integerList = List<int>.generate(2000, (index) => index);
This gives us a list of integers from 0 to 1,999, with a total of 2,000 integers.
A scrollable Column
Next, let us try creating a series of Text widgets in a Column that we have made scrollable. Here is what that would look like:
class MyScrollingList extends StatelessWidget {
const MyScrollingList({super.key});
@override
Widget build(BuildContext context) {
final List<int> integerList = List<int>.generate(2000, (index) => index);
return SingleChildScrollView(
child: Column(
children: <Widget>[
for (final int i in integerList)
ListTile(
title: Text('$i'),
),
],
),
);
}
}
Runnable copy: examples/flutter_for_jobseekers_ch11/lib/scrolling/column_list.dart
Let us run this in profile mode and scroll the list a bit to see what the performance looks like. As you can see in Figure 11.23, there is a lot of jank when scrolling this list. Even though our app is incredibly simple, consisting only of a column of 2,000 ListTile widgets, each displaying a single integer, scrolling the list causes jank. Running the same code on a less powerful machine than a high-end computer, such as a smart phone, would certainly result in even more jank.

Figure 11.23: There's a lot of jank when scrolling
ListView.builder
Now, let us rewrite this to use a ListView widget. In this example, we have removed the SingleChildScrollView and the Column, replacing both with the ListView.builder(). We tell the ListView how many items there will be in the list using the itemCount parameter, then use the itemBuilder to build the ListTile widgets. Note that there is no longer a for-loop in this code, as the builder takes care of this for us:
class MyScrollingList extends StatelessWidget {
const MyScrollingList({super.key});
@override
Widget build(BuildContext context) {
final List<int> integerList = List<int>.generate(2000, (index) => index);
return ListView.builder(
itemCount: integerList.length,
itemBuilder: (BuildContext context, int i) {
return ListTile(
title: Text('$i'),
);
},
);
}
}
Runnable copy: examples/flutter_for_jobseekers_ch11/lib/main.dart
Now that we have updated our code, let us run the same test: scroll the list of integers and see what the performance looks like (Figure 11.24). What we are looking for here is a performance improvement, ideally in the form of frames being rendered in less time and with no jank present.
ListView is far more efficient, but why?
Figure 11.24: Scrolling performance of a ListView
Why the ListView is faster
Column
Column is created, all its children are built each frame. When we have 2,000 ListTile widgets being built each frame, that is a lot of work for the CPU to handle, especially when we start scrolling. If we are not scrolling, Flutter is smart enough not to perform any unnecessary widget rebuilds because it knows that there is no animation happening, no state changes, and performing a rebuild of the widget would give us the same widget we started with. Thus, when no action is taken, the build process never happens.ListView
ListView will build only the widgets displayed on screen (plus a couple on either end, if applicable) at any given time. If the constraints of our list are such that only three items can fit on the screen at any given time, only about 5-10 or so widgets will be built. (That is the three that are on screen, and a couple each on the above and below.) When the list is scrolled, widgets falling outside of the possible range where they are either shown on screen or could immediately be shown on screen are removed from the widget tree, freeing memory in the process.In that instance, it does not matter how many widgets we have built… or does it? It does, in fact, matter. Each widget consumes memory. If, instead of displaying an integer, we had a list of images, the memory size would balloon out of control as all 2,000 images were being loaded into memory when the Column was initially built, and then every frame as we scroll.
Column's children each frame. The runnable copy's tests count builds and paints per item while scrolling a test-only copy of this list: none of the 2,000 items is rebuilt, but all 2,000 are painted again, because a Column paints every child whether or not it is on screen. Since nothing is rebuilt, images would not be loaded again every frame either; the memory problem is that all 2,000 stay in memory.This is precisely why the ListView is so much more performant than a Column when dealing with a large list of children. That is not to say a Column does not have its place — it absolutely does — but knowing the difference between the two can mean the difference between an application with jank and an application with smooth scrolling.
The shrink-wrapped ListView
So, back to the original question: when is a ListView not a ListView?
ListView. Normally, the ListView will fill its constraints, culling off-screen widgets in the process. However, if we specify the shrinkWrap: true property, the entire widget will act more like a Column.This could be useful if you needed a small number of widgets in a list, each being built using a builder rather than composed independently and inserted into a Column. It is not an impossible situation to imagine. However, not understanding the implications of setting the property on a much larger list can lead to problems. Let us look at an example:
class MyScrollingList extends StatelessWidget {
const MyScrollingList({super.key});
@override
Widget build(BuildContext context) {
final List<int> integerList = List<int>.generate(2000, (index) => index);
return SingleChildScrollView(
child: ListView.builder(
shrinkWrap: true,
itemCount: integerList.length,
itemBuilder: (BuildContext context, int i) {
return ListTile(
title: Text('$i'),
);
},
),
);
}
}
Runnable copy: examples/flutter_for_jobseekers_ch11/lib/scrolling/shrink_wrap_list.dart
ListView has its own scrollable, takes the drag, and has nowhere to scroll, so the SingleChildScrollView never moves (a mouse wheel, as on the book's desktop, still scrolls it). The runnable copy adds physics: const NeverScrollableScrollPhysics() to the ListView, which hands the drag to the SingleChildScrollView; its tests check both behaviors. It still builds all 2,000 ListTiles.Here, we have taken our highly performant ListView and added the shrinkWrap: true property, then wrapped the whole thing in a SingleChildScrollView. We will perform the same scrolling performance test as before, with the results as shown in Figure 11.25:

Figure 11.25: Jank introduced by treating a ListView like a Column
Without a doubt, there is a lot of jank, and the frame times are way up. As you can see, even though we are using the much more performant ListView.builder() rather than a Column, we have similar or worse performance. Understanding how widgets work and which to use in each scenario is key to building a highly performant application.
Finding the problem with the tools
However, this example was tailored specifically to showcase this single widget. How can we identify the problem in our own applications using these tools? Let us start by selecting one of the janky frames, then start examining the event details (Figure 11.26):

Figure 11.26: Zooming into the timeline details of one of our janky frames
By zooming in, we can see that there are probably about 2,000 DisplayList events each frame. Remember that you can also toggle on tracking widget builds to make things even more clear. Using this information, we can tell that our list is rebuilding every item in the list, every frame. With that knowledge, we should have enough information to start tracking down the problem. If we rerun the application in debug mode to gain access to the widget inspector, we can very quickly identify the problem (Figure 11.27):
ListView wraps each item in a RepaintBoundary, and the tests find that scrolling repaints none of the 2,000 items; where the frame time goes instead, the tests do not show. What they do confirm is the next figure: all 2,000 ListTiles are live.
Figure 11.27: Our Widget Tree has 2,000 ListTiles in it with 2,000 live children.
The render object for our list will tell us precisely how many children are currently live, or actively being built. Note the estimated child count a couple of lines above, which states the estimated total child count. In contrast, if we look at our optimized ListView example without the shrinkWrap: true property being set, we can see there are still an estimated 2,000 children, but only 20 of them are currently live (Figure 11.28):

Figure 11.28: Our widget tree has only 20 ListTiles with 20 live children.
ListTiles in the tree: 2,000 for the Column and for the shrink-wrapped ListView, fewer than 30 for ListView.builder (also after scrolling).Here, we have looked at just one example of a built-in widget which can go awry if we are not careful. There are many other widgets which can have similar problems if we are not careful, but at least we have the tools to identify these issues when something goes wrong. But what are some best practices to keep in mind so that we do not put ourselves in this place to begin with?
Optimizing widgets
As we know, the build() method of a widget is run each time the widget is rebuilt, which could be upwards of 60-120 times each second. If our aim is to make sure that we avoid jank, we need these rebuilds to happen as efficiently as possible. Thankfully, there are several things we can do to ensure that rebuilds are doing as little work as possible.
Avoid functions in build()
Cache
CachedNetworkImage widget, which will store the image in the application's local cache upon fetching it for the first time. The next time the widget is rebuilt, the cache will be checked first and the image there will be used if it exists; otherwise, the image will be fetched from the internet.CachedNetworkImage is not part of Flutter; it comes from the cached_network_image package on pub.dev. (added, not in the book)Caching can be used in all sorts of ways, not just with images. It may be possible to cache some API calls, at least for a period, before invalidating the cache due to some sort of timeout. This means that a widget calling an API does not need to make dozens of calls each second, saving network bandwidth and speeding up the widget build.
Smaller widgets
Not only will this give you more re-usable code, but it will help prevent unnecessary widget rebuilds. If you have broken your header off into its own widget, it is far less likely to be rebuilt unnecessarily when part of the application's main content calls for a rebuild.
Your IDE likely has a line running down it by default, marking the 80-character line (Figure 11.29). If the code for your widget tree is regularly bumping up to this line or even running past it, that should be a clue to you that your widgets might be nested too deeply, and it is time to refactor your code.
Not only will your code be more readable and easier to debug when the widgets are smaller, but you will be forced to think more deliberately about how you compose your widgets. The performance improvements will come as Flutter will only rebuild widgets which require a rebuild, allowing it to keep widgets that do not. If your entire application is a single widget, that widget will always be rebuilt in its entirety.

Figure 11.29: Highlighting the 80-character line in Visual Studio Code
Pass only what the widget needs
Finally, be conscientious about the parameters you are passing into your widgets. It may be convenient to pass in a large object to pull out multiple values for the widget you are building, but that might mean making a copy of that object in memory and will require more CPU time to process each time the widget is built than if you had simply passed in the variables you needed in the first place.
If you are using BLoC, it is tempting to pass the BLoC state from a BlocBuilder into several of the child widgets being built. However, that is unlikely to be an efficient way to build the widgets. Instead, pull out the variables you need from the state and pass them directly in as parameters. The resulting widgets will even be easier to read and debug, since you will know ahead of time if the parameters you are passing in are properly set, rather than doing checks inside that widget's build method.
These are only a few suggestions to keep in mind when building widgets optimally, and it is by no means an exhaustive list. It will take practice and experience to learn what causes jank, balloons memory usage, and contributes to an application that is underperforming your expectations. There are more suggestions in Flutter's online documentation concerning optimizing performance, which you can view here: https://docs.flutter.dev/perf.
Conclusion
Learning to use Flutter to build applications is not something you can do only by reading a book. It requires experimentation, failure, analysis, and eventual understanding. Fortunately, Flutter ships with a robust set of tools, DevTools, which give you everything you need to build your understanding. Even the most seasoned Flutter developers will use these tools constantly, having integrated them into part of their everyday workflow.
Flutter was designed from the very beginning to be highly performant, and while premature optimization of your widgets is not recommended, sometimes it is necessary to dig deep into your application to understand why it is not buttery smooth. When that happens, you have got the tools available to analyze and dig into precisely what is happening, thanks to Flutter's profile mode.
Up to this point in the book, we have been learning a lot about different concepts when it comes to developing applications using Flutter. In the upcoming chapter, we are going to take all these concepts and put them to use. We will explore what it might be like to have a client with a set of ideas, business needs, and a design — then turn all of it into a fully-functioning application. This is what we have been building up to, and you have everything you need to be successful. So, let us go build an application!
Questions
- What is the difference between debugging and troubleshooting?
- What are the five steps involved in debugging?
- What methods can you use to log information to the debug console?
- What is a breakpoint, and how do you create one?
- What is a stack trace? What is a stack frame?
- What is an exception?
- What risks do you run by using a
try/catchblock? - How do you access Flutter's DevTools?
- What are the different tools available in Flutter's DevTools?
- What are the two different categories of performance issues your application may encounter?
- What is vsync and how does it relate to your application's performance?
- What is jank?
- What three compilation modes are available for Flutter applications? How do they differ?
- What is the difference between storage and memory?
- When is a
ListViewnot aListView? - When should you consider optimizing your application?
- What are some steps you can take to optimize your application?
Key terms
Further reading
References
- BPB Publications. (n.d.). Flutter for Jobseekers (companion code repository). Retrieved from GitHub: https://github.com/bpbpublications/Flutter-for-Jobseekers (added, not in the book)
- Dart. (n.d.). Variables. Retrieved from Dart: https://dart.dev/language/variables (added, not in the book)
- Flutter. (n.d.-a). Use the Performance view. Retrieved from Flutter: https://docs.flutter.dev/tools/devtools/performance (added, not in the book)
- Flutter. (n.d.-b). Use the Memory view. Retrieved from Flutter: https://docs.flutter.dev/tools/devtools/memory (added, not in the book)
- Flutter. (n.d.-c). Use the Network view. Retrieved from Flutter: https://docs.flutter.dev/tools/devtools/network (added, not in the book)
- Flutter. (n.d.-d). saveLayer method. Retrieved from Flutter API: https://api.flutter.dev/flutter/dart-ui/Canvas/saveLayer.html (added, not in the book)
- flutter/devtools. (2024). Memory: enable allocation tracing for profile mode. (issue #5174). Retrieved from GitHub: https://github.com/flutter/devtools/issues/5174 (added, not in the book)
- flutter/devtools. (2025a). The "Network" tab should provide visibility into non-HttpClient HTTP traffic (issue #4829). Retrieved from GitHub: https://github.com/flutter/devtools/issues/4829 (added, not in the book)
- flutter/devtools. (2025b). Network page does not show requests when running on Hyper-V (issue #4997). Retrieved from GitHub: https://github.com/flutter/devtools/issues/4997 (added, not in the book)
- flutter/flutter. (n.d.). print.dart and basic.dart (Flutter 3.29.0 source). Retrieved from GitHub: https://github.com/flutter/flutter/blob/3.29.0/packages/flutter/lib/src/foundation/print.dart (added, not in the book)
- Microsoft. (n.d.). Debug code with Visual Studio Code. Retrieved from Visual Studio Code: https://code.visualstudio.com/docs/debugtest/debugging (added, not in the book)
Reactivity and Platform-Specific Considerations
Responsive layouts with LayoutBuilder, dart:io and its limits, app icons and splash screens, platform styles and navigation, and flutter_platform_widgets.
Creating Your First Application
Turning a weather-app design and requirements into a plan, organizing project files, enums and Freezed code generation, and building the API layer.