Introduction to Widgets
Introduction to Widgets
In this chapter, we will discuss the different types of widgets and explore some of the most used ones that you will run across, look at our sample application and explore each of the widgets it is composed of, and briefly discuss the architecture of Flutter to understand the widget lifecycle.
Example 4.1–Example 4.27 in the Chapter 04 folder; each code block below is labelled with its example number. The repository's constructors use the older {Key? key}) : super(key: key) form instead of {super.key}, and it has conversion glitches of its own, so the code on this page follows the book (BPB Publications, n.d.).Chapter overview
Structure
- Briefly exploring the default Flutter application
- What is a widget and how is it drawn to the screen?
- Stateless widgets
- Stateful widgets
- Inherited widgets
- Introduction to BuildContext
- Exploring and modifying the Flutter demo
Objectives
Runnable example
MyHomePage, MyWidget, MyCustomTextWidget, ExampleWidget, MyInheritedWidget) are also available as a runnable project with widget tests in examples/flutter_for_jobseekers_ch04/. The code on this page is shown as the book prints it.Briefly exploring the default Flutter application
Take a moment to play around with the application you have just gotten running from the last chapter. It is a very simple application, with only a single button. Tapping the button increases the counter at the center of the screen. Let us look at the code to see what is going on. Do not worry if none of it makes sense – that is why you are reading this book!
Back in Visual Studio Code, you should see a list of files on the left side of the window. If not, look for the vertical bar of icons and click the one on the top which looks like a couple of stacked pages. Right now, we can ignore everything except a folder named lib, which we can expand to find the star of the show: main.dart. Double click main.dart to open it in the editor.
The Flutter team has done a great job of documenting most of the code, so it is worth reading over their comments. (Comments in Dart are typically written as a line of text preceded by //). There are a few things here that we are going to look at that are not covered by the comments. First, you will notice these lines at the top:
void main() {
runApp(const MyApp());
}
main() — the entry point
main() function. Anything that your program does that is not inside of the main() function will have been called by something else that was in the main() function.runApp() — where Flutter starts
runApp() function. This function tells Flutter where to start running its code. Flutter is written in the Dart programming language, which can be used to create far more than just Flutter applications. Sometimes, your application will execute Dart code before the Flutter code is ever invoked. The runApp() function has a single parameter: the Widget which will be the root of your application.We will get into what widgets are shortly, but there's one last thing you will want to know.
If you scroll down in the file a bit, you will find a line that says return Scaffold(. Just below that, you will find a line that says body: Center(. As we move into this chapter, you will undoubtedly want to follow along. You can do so by selecting the Center widget and deleting it. Then, you will put the examples where the Center widget once was.
Center( and everything up to the closing parenthesis, then delete it. However, you should leave the body: at the start.What we're looking for is as follows:
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created
// by the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body:
floatingActionButton: FloatingActionButton(
Any time you want to try out an example in this chapter, you will put the code just to the right of the body: section. If that feels overwhelming right now, do not worry. You are not expected to understand anything, yet! You soon will, though. Just as soon as we talk about what the heck a widget even is.
What is a widget and how is it drawn to the screen?
Broadly speaking, a widget could be anything; it could be a box, an ink pen, a shoelace. What these three items have in common is that they are all small, simple, and purpose-built. They each do one thing, and they do it well.
Widgets in Flutter are also small, simple, and purpose-built. You will find widgets such as TextArea, Container, and Column. Each of these widgets has one job: provide a user with a place to enter text, hold another widget, or create a vertical stack of widgets, respectively.
TextArea widget. The widget that provides a place to enter text is TextField ("A Material Design text field."), which also handles multi-line input through its maxLines property (Flutter, n.d.-c).Even some of the most complex widgets, such as the Material widget, are built using other widgets. (In the case of Material, an AnimatedDefaultTextStyle, NotificationListener, and AnimatedPhysicalModel are used.) So, understanding widgets is vital for understanding Flutter. To fully understand widgets, we need to talk about how widgets are rendered to the display.
Each widget has a build() method. When Flutter wants to render a widget, build() is called, the state of the application is evaluated, and a widget is returned. The widget which is returned could be a simple widget with no children, or it could have one or more children which each have its own build() method and potential child(ren). This process happens continually, always evaluating the current state of the application and returning new widgets where necessary. In almost every case, the returned widget(s) will be composed of other, more primitive widgets.
Collectively, these widgets are assembled into a widget tree, which Flutter uses to build its element tree and eventually its render tree. We are going to explore the element and render trees later in this chapter, so for now let us look at the widget tree using the following example:
Container(
color: Colors.lightBlue,
child: Row(
children: const [
Image(
image: NetworkImage(
'https://flutter.github.io/assets-for-api-docs/assets/widgets/owl.jpg'),
),
Text('Flutter is fun!'),
],
),
)
This code will create a Container widget, colored light blue, with a row of widgets contained within. The Row consists of two widgets: an Image widget and a Text widget. Once inserted into our application, this is what we will see (figure 4.1):

Figure 4.1: The results of our test code, running as a Windows application.
On the surface, the widget tree we have created appears quite simple (figure 4.2):

Figure 4.2: The widget tree from our example code
In practice, however, the widget tree Flutter created is somewhat more complex (figure 4.3):

Figure 4.3: The actual widget tree Flutter builds from our example.
Constraints and sizes
Each widget is passed down a set of constraints from its parent, while simultaneously passing its size back up the tree. This concept of constraints and sizes is key to composing a UI in Flutter.
Constraints
Size
We can explore this behavior with the following code (figure 4.4):
Container(
width: 100,
color: Colors.blue,
child: Row(
children: const [
Text(
'This text will overflow its constraints.',
softWrap: false,
overflow: TextOverflow.visible,
),
],
),
)

Figure 4.4: The error is thrown when a widget's size exceeds its given constraints.
The Row widget is very fussy about its constraints not being violated. By constraining a Row within a Container, we can limit the constraints of the Row. (Without doing this, the Row will expand to the size of the canvas, or whatever other parent's constraints have been passed down.) Once we have constrained the Row, we add a single child element, a Text widget, and provide arguments which will ensure the text does not wrap or clip if it runs over its given constraints.
Now that we understand what a widget is and how it's rendered to the screen, let us talk about the three different types of widgets, starting with stateless widgets.
Stateless widgets
Stateless widgets are the simplest of the three types of widgets, both in how they are created and used, and in their functionality. They are mostly used to describe the user interface. Importantly, stateless widgets are widgets that do not require a mutable state. However, they can have constructor arguments.
A constructor parameter allows you to pass a variable into the widget, called an argument, and is used during the build() method to customize the look, feel, behavior, or other aspects of the widget as part of the widget's properties. The build() method of a stateless widget is typically only called when:
- the widget is first inserted into the widget tree,
- the widget's parent changes, or
- one of its dependent inherited widgets changes.
StatelessWidget is its own abstract class, meaning it is used to define the core behavior of all classes which are based on it, but it cannot itself be instantiated.Let us look at some of the more common stateless widgets which are part of the default Material package and their use cases, and then we will delve into creating our own.
Container
One of the most common of all the stateless widgets is the Container widget. It is used as a layout widget, which can have a single child widget. Container might sound like a boring widget, but it is one of the most versatile out there with over a dozen properties available! The best way to describe Container is with an example. In our example, we are going to take things to the extreme by setting many, but not all, of the available properties. Look at our example Container (figure 4.5):
Container(
width: 100,
height: 100,
margin: const EdgeInsets.only(
top: 20,
left: 100,
),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.grey[50],
),
child: const FlutterLogo(),
padding: const EdgeInsets.all(30.0),
foregroundDecoration: BoxDecoration(
border: Border.all(
width: 5,
color: Colors.grey,
style: BorderStyle.solid,
),
gradient: const RadialGradient(
colors: [
Colors.white,
Colors.white,
Colors.black,
],
),
shape: BoxShape.circle,
),
)

Figure 4.5: The resulting widget which is rendered from our example.
You might be asking yourself where you can find all the available properties for Container, or any other widget. There are several ways to do this:
Hover in the editor
Online documentation
Source code
Column and Row
Both the Column and Row widgets function similarly, taking in a list of widgets and displaying them sequentially, with Column ordering its children vertically and Row ordering them horizontally. Columns and Rows are well suited for grouping items together. For example, you might use a Row to place an icon next to a text label, as in this example (figure 4.6):
Row(
children: const [
Icon(Icons.account_circle),
Text('My Account'),
],
)

Figure 4.6: Using a Row to align two widgets.
By swapping out the Row for a Column, you would find that the Icon would be placed above the Text. By leveraging the mainAxisAlignment and crossAxisAlignment properties, we can further adjust the alignment of the child widgets. In the following example, the mainAxisAlignment property has been modified so that the elements will have equal space between them. We have also added another Text widget to further illustrate this behavior (figure 4.7).
Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: const [
Icon(Icons.account_circle),
Text('My Account'),
Text('Another widget')
],
)

Figure 4.7: Changing our Row to a Column, adding another child, and adjusting the alignment.
Column widget centers its children horizontally. This behavior can be changed by using the crossAxisAlignment property. Both Column and Row are indispensable when composing a user interface in Flutter.Text
We have already seen the Text widget several times before in our examples, so let us take a minute to look at it more deeply. Displaying text is a surprisingly complex and nuanced task, especially when one considers the massive number of scripts (of which Latin is but one), typefaces, and styling options available. All this is before we even consider what happens to the text when it overflows its constraints! Fortunately, Flutter's Text widget has us covered.
Displaying some text in the default style is as easy as passing a string of text into your Text widget as a positional parameter, meaning there is no need to specify a parameter name (see figure 4.8).
Text("Flutter is fun!")

Figure 4.8: Displaying text using the DefaultTextStyle.
The Flutter framework defines its default text style in the DefaultTextStyle widget, which is quite appropriately named. This is then made available to widgets through the app's Theme. If we want to override the default text style, we can do so by specifying a style using the style parameter, where we can supply our own TextStyle, which will override the DefaultTextStyle for any of the arguments we supply (see figure 4.9).
Text(
"Flutter is fun!",
style: TextStyle(
backgroundColor: Colors.grey[300],
fontFamily: 'Neonderthaw',
fontSize: 36,
wordSpacing: 24,
),
)

Figure 4.9: Overriding the default text style.
What if we want to make our text larger and bold, center it in the parent container, and have a colorful border around the letters? With Text, that's a simple enough task (figure 4.10). In fact, we can even use a cascade notation to apply multiple properties.
Text(
'Fancy text',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 72,
fontWeight: FontWeight.bold,
foreground: Paint()
..style = PaintingStyle.stroke
..strokeWidth = 3
..shader = ui.Gradient.linear(
const Offset(0, 20),
const Offset(300, 20),
<Color>[
Colors.blue,
Colors.red,
],
),
),
)

Figure 4.10: Some truly fancy text.
Cascade operators let us perform multiple actions on the same object in a shorthand form. Let us compare non-cascade notation to the same code using cascade notation:
import 'dart:ui' as ui;
// Non-cascade notation
final Paint paint = Paint();
paint.style = PaintingStyle.stroke;
paint.strokeWidth = 3;
paint.shader = ui.Gradient.linear(
const Offset(0, 20),
const Offset(300, 20),
<Color>[
Colors.blue,
Colors.red,
],
);
// Cascade notation
Paint()
..style = PaintingStyle.stroke
..strokeWidth = 3
..shader = ui.Gradient.linear(
const Offset(0, 20),
const Offset(300, 20),
<Color>[
Colors.blue,
Colors.red,
],
);
Companion code: Example 4.11 shows the two versions in the opposite order: cascade notation first, then non-cascade notation.
What happens if we want to change font styles in the middle of a sentence, though? For example, what if we wanted to add some emphasis to a particular word in our text? This requires a somewhat different strategy, because we will need to tell Flutter exactly what text we want to have styled and what style to use. We do this by using the Text.rich constructor, that wants a TextSpan as its positional argument. Confused? Let us look at an example (figure 4.11).
Text.rich(
TextSpan(
text: 'Flutter',
children: <TextSpan>[
TextSpan(
text: ' is ',
style: TextStyle(
fontStyle: FontStyle.italic,
),
),
TextSpan(
text: 'fun!',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
],
),
)

Figure 4.11: Styling in-line text using multiple styles.
Text and its constraints
Before we move on to the last stateless widget that we are going to look at right now, let us have a look at how text behaves when its constraints change. In the preceding examples, there was plenty of room for our text, but if we limit the constraints of the Text widget, Flutter will have to do something with the text as it runs up against those constraints. By default, Flutter will wrap the text to the next line, although this behavior can be prevented by setting the softWrap parameter to false (figure 4.12).
Container(
color: Colors.grey[300],
width: 105,
height: 105,
child: const Text(
"Your text will automatically wrap to the next line, but what happens if it overflows its parent?",
),
)

Figure 4.12: Flutter will wrap text to the next line for us by default.
A keen-eyed observer will note, however, that our text gets cut off when it no longer has room to wrap! We could fade out the text as it gets closer to the edges of its parent (figure 4.13):
Container(
color: Colors.grey[300],
width: 105,
height: 105,
child: const Text(
"Your text will automatically wrap to the next line, but what happens if it overflows its parent?",
overflow: TextOverflow.fade,
),
)

Figure 4.13: Fading out text which would otherwise be cut off.
Alternatively, we could simply truncate the text with an ellipsis, preventing it from wrapping to the next line altogether (figure 4.14). We do this by specifying an overflow property with the TextOverflow.ellipsis argument.
Container(
color: Colors.grey[300],
width: 105,
height: 105,
child: const Text(
"Your text will automatically wrap to the next line, but what happens if it overflows its parent?",
overflow: TextOverflow.ellipsis,
),
)

Figure 4.14: Truncating the overflowing text with an ellipsis.
As you can see, there is a lot of power and flexibility within the Text widget. There are even more options, which we haven't discussed here, that can modify your text to display right-to-left, change the relative character widths and heights, and much more.
Center
If you ask a Web developer to center an element on the page both horizontally and vertically, they may sigh before writing several lines of code, using one of many different methods. Internally, they will be glad that they now have modern tools to accomplish that task, as a few short years ago it was a much more difficult proposition.
Accomplishing the same task in Flutter is as simple as using the Center widget (see figure 4.15).
Center(
child: Text("Flutter is fun!"),
)

Figure 4.15: Centering an element in Flutter is easy with the Center widget.
Creating a custom stateless widget
Sometimes you will find yourself reusing a group of nested widgets. If this happens, you might be tempted to copy and paste the whole tree of widgets, but what happens when you need to make a change to one of the elements in that tree? It would not make sense to go back through your code and find every place you have copied that code to so you can update the same element, in the same way, multiple times.
To create a stateless widget, start with this boilerplate:
class MyWidget extends StatelessWidget {
const MyWidget({super.key});
@override
Widget build(BuildContext context) {
return Container();
}
}
Runnable copy: examples/flutter_for_jobseekers_ch04/lib/stateless/my_widget.dart
We use class MyWidget extends StatelessWidget to tell Flutter that we are creating a new class of Widget called MyWidget which is based on the class StatelessWidget. Let us examine what is happening here, line by line.
Lines 1–2: the class and its constructor
On the first line, we are defining our widget as MyWidget and telling Flutter to use StatelessWidget as the basis for doing so. Line two is our constructor. The const keyword tells Flutter that instances of the widget may have constant values when the code has been compiled, provided that all the properties are marked as final. On that same line, you will see MyWidget({super.key}), but what does this mean? Come to think of it, what does super.key mean?
To answer these questions, we must dive a bit more deeply. First, we have MyWidget({super.key}). You will notice this includes the name of our widget. That makes sense since we are defining a constructor for that widget. But what is key, why is it super, and why is it in curly braces?
Key is used to control which widgets the framework matches up with the corresponding state object for that widget when a rebuild is triggered. In practice, this allows Flutter to preserve its state (which we will talk about more in the next section) when widgets move around in the widget tree. For the most part, you will not need to manually specify a Key.Think back to when we were exploring the Text widget. When we wanted to print text to the screen, we first invoked the widget, and then set several of the widget's properties. The first was the text we wanted to display, followed by everything else. But did you notice that we did not have to specify Text(text: "Our text") when we wanted to just print some text? Instead, we just wrote Text("Our text"). In the first example, which is the wrong way to create a Text widget, we are specifying the text that we want the widget to display as a named parameter, rather than as a positional parameter, as in the second (and correct) example.
This is where the curly braces come into play. Any variable we specify in our constructor that is inside the curly braces will be a named parameter. Any parameters specified outside of the curly braces will be a positional parameter. It is also important to note that positional parameters are required, by default.
Here is an example of a widget with a positional parameter:
class MyCustomTextWidget extends StatelessWidget {
final String text;
const MyCustomTextWidget(this.text, {super.key});
@override
Widget build(BuildContext context) {
return Text(text);
}
}
Runnable copy: examples/flutter_for_jobseekers_ch04/lib/stateless/my_custom_text_widget.dart
text within our build() method, we need to also specify final String text;. The same will be true for any parameter, regardless of whether it is a positional or named parameter.Sound null safety
Finally, we will answer the question of why the Key parameter is super. Starting in Dart 2.12 and Flutter 2, sound null safety was enabled by default. In computer science, null means "nothing." So, if we simply define a variable and do not set it to a value, the value would be null. This fact alone has caused a great number of headaches for developers and bugs and crashes for users.
So, how do we prevent those headaches and crashes? Easy! We make sure that our variables are not null unless we say they can be! To accomplish this, variables can be marked nullable by adding a question mark after the type.
final String myString
final String? myString
myString is String, but we will also allow for its type to be null. So, myString can either be a String object or null.Inheriting the key with super
When creating a class in Dart, we can inherit a property from the immediate parent object. We do this by using the super keyword. In earlier versions of Dart and Flutter, the syntax was slightly different, and by examining it we can start to see where the current implementation came from. In previous versions, the code would have been written as const MyCustomTextWidget(this.text, {Key? key}) : super(key: key); which makes it clearer that the key property is a nullable, named parameter. By using super(key: key), the key property will be inherited from the parent object if it is not specified. This means we can optionally specify a Key when creating an instance of our widget.
Key controls how one widget replaces another widget in the widget tree. Two widgets with the same key must have the same runtimeType, so do not go replacing a stateless widget with a stateful widget, unless you want to give Flutter a headache!In modern Dart and Flutter, the constructor has been shortened to allow for the parameter to be specified as super.key, but the result is the same as before.
Lines 5–7: build()
Lines 5 and 6 of our custom widget go together. Line 5 says that we want to override the default build() function of the StatelessWidget on which we are basing our custom widget off. Line 6 starts with Widget, which is the build() function's return type. That is, when the build() function runs, we expect that a Widget will be returned after all is said and done. The Flutter framework itself will call the build() method automatically, so there is no need to invoke it manually. The parameter which is passed to build() is a positional parameter of type BuildContext and is named context. We will talk more about what BuildContext is later in this chapter. For now, just know that it is passed into our build() method.
Finally, on Line 7, we compose our new widget and return it. The build() method will always have a return statement, followed by what value it is returning (and that value will always return a Widget.) What happens within that return statement is up to you! That is where you will specify the nested widgets that you would like to return to save yourself a whole lot of time and energy, ensure your code is concise and readable, and make testing your application so much easier.
Stateful widgets
An application built entirely with stateless widgets would be very boring, indeed. Sometimes, we want to add interactivity to our app. Whether this is in the form of a button to push, some text that updates according to another action (such as with the counter in the Flutter demo application, from the previous chapter), or any other type of interactivity, stateful widgets are where we need to turn to.
Stateful widgets are widgets which can create and maintain a custom State object. In contrast to a stateless widget, stateful widgets can keep changes made to them when a rebuild is triggered, via the State object. Let us look at the MyHomePage widget from the demo application, so we can start to understand how all the pieces fit together.
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
Runnable copy: examples/flutter_for_jobseekers_ch04/lib/main.dart
textTheme.headline4 no longer compiles. The 2018 TextTheme names were replaced by the Material 3 names in Flutter 2.10 (headline4 → headlineMedium) (Flutter, 2021), and the old names were removed in Flutter 3.22 (Flutter, 2024). Current code uses Theme.of(context).textTheme.headlineMedium, as the runnable copy does.The first thing you will notice is that a stateful widget has two parts:
The widget — MyHomePage
There is a constructor which has a required title named parameter. Below that, we see that the title is being defined as a String type. This should all make sense to you by now.
Where the stateful widget differs from the stateless widget is that there is no longer a build() method. Instead, we override the createState() method. This is where we tell the stateful widget what State object to use.
The state — _MyHomePageState
_MyHomePageState that the widget's build() method is contained. Any variables that we want to be preserved between rebuilds are defined outside of the build() method and in this example, that includes the _counter variable. When this variable is defined initially, it is set to 0. Whenever the _incrementCounter() method is called, the state of the widget is updated to add 1 to the old value, eventually resulting in a rebuild being triggered._MyHomePageState class starts with an underscore. The underscore indicates that the variable or method is scoped locally to the library in which it can be found. A library can be a single file or multiple files connected with the part and part of keywords. This is used to tell Flutter that we're defining a private object. A private object cannot be directly invoked from outside its context. You will see this inside the class, too, with the _counter variable and the _incrementCounter() method. Going back to our MyHomePage widget, what we find is that the State object which is being created is called _MyHomePageState, which is a private class. Now we know that this State object should not be referenced anywhere except from the widget which invokes it.Setting the state
This brings us to the next concept of stateful widgets: setting the state. When a stateful widget is first added to the widget tree, the initState() method is called. The _MyHomePageState widget does not have an initState() method defined, though, so what gives? Well, remember when we said we must override the build() method? It is the same concept with the initState() method (and the other state management methods) except that this time, it is optional. If we want to override the default behavior, we need to add a method, like this:
@override
void initState() {
super.initState();
}
super.initState(); line is important because it will run the initState() method of the widget that you have based your custom widget on. Anything you want to add to the initial state of the widget should be done after this line.So, what would you want to add to an initState()? Generally, this is where you would start to invoke some sort of logic. Perhaps you have a widget which will display the results of a Future. Consider the following code:
Future<bool> _futureFalse() async {
return Future.delayed(const Duration(seconds: 1), () {
return false;
});
}
This method will wait one second before returning false. If you wanted to wait for this future to complete before building your widget for the first time, you could invoke the method from within the initState() and assign it to a variable. Here is how we would do that:
class ExampleWidget extends StatefulWidget {
const ExampleWidget({super.key});
@override
State<ExampleWidget> createState() => _ExampleWidgetState();
}
class _ExampleWidgetState extends State<ExampleWidget> {
bool alwaysFalse = true;
Future<bool> _futureFalse() async {
return Future.delayed(const Duration(seconds: 1), () {
return false;
});
}
void _resolveFutures() async {
alwaysFalse = await _futureFalse();
setState(() {});
}
@override
void initState() {
super.initState();
_resolveFutures();
}
@override
Widget build(BuildContext context) {
return Text('$alwaysFalse');
}
}
Runnable copy: examples/flutter_for_jobseekers_ch04/lib/stateful/example_widget.dart
When the widget is created and the build() method runs, the text displayed will initially be true as we set the alwaysFalse variable to true when we defined it on Line 9. Since initState() is called before build(), the _resolveFutures() method is already running and has already invoked the _futureFalse() method by the time the build() process even starts. However, it takes a single second for that process to complete, so after that second the text is updated within the widget to display false when a rebuild is triggered.
setState() method (Line 19) to update the state of the widget and trigger the rebuild. If we had not done that, the variable would have been updated but no rebuild would have happened, so the text on the screen would not have changed.The lifecycle of a stateful widget
The lifecycle of a stateful widget includes the following steps:
createState()
We have seen several of these steps so far in our example. createState() is called from our stateful widget, whereas initState() is called from the State widget.
mounted == true
In between, we have mounted == true. This condition is set once a widget has had a BuildContext assigned to it.
initState()
Called from the State widget when the stateful widget is first added to the widget tree.
didChangeDependencies()
After the state has been initialized, the didChangeDependencies() method is called. This will be called both right after the state has been initialized and whenever data that the widget depends on changes.
build()
Next up is our trusty build() method, which we are well acquainted with.
didUpdateWidget()
This is called when the widget's configuration changes, which is often something the parent widget is responsible for, triggering a rebuild for our stateful widget. The usage of this method is a bit more nuanced but can be thought of as a replacement for the initState() method, but only in cases where the widget associated with the widget's state needs to be rebuilt.
setState()
Next, we have setState(), which we are already familiar with.
deactivate()
This is rarely used, but since a widget can be removed and reinserted into the widget tree at a different location, there exists a method to call in that event.
dispose()
When a State object is removed from the widget tree, the dispose() method is called. This is where you will want to call the methods to stop any animations, unsubscribe from data streams, and do a bit of housekeeping to clean up after yourself.
mounted == false
Once a widget has been disposed of properly, the mounted variable is set, internally, to false.
initState() is called versus build() will save you many headaches in the future.Some common examples of stateful widgets include things like buttons, radio buttons, checkboxes, sliders, switches, and anything else that can be interacted with to perform some sort of action.
Inherited widgets
Inherited widgets are the third and final type of widget which is available to us in the Flutter toolkit. These widgets are often the least understood, and thus the most neglected by most new Flutter developers. We are going to demystify them and explore their genius and beauty. So, what is an inherited widget?
Let us say you are building an application, and you want to pass some data down the widget tree. Maybe this is some text, named myText, and you want to display it in an ancestor widget (see figure 4.16).

Figure 4.16: How do we pass down data to ancestors in the widget tree?
InheritedWidget as the "Base class for widgets that efficiently propagate information down the tree", and the context that looks it up "must be a descendant of the InheritedWidget" (Flutter, n.d.-b). The same applies to "ancestors" in the figure caption and in the Inherited widget key term below.We could modify each of the widgets in the tree to accept a parameter and use that to pass down the data manually, but this is cumbersome and prone to all sorts of issues. Luckily, the Flutter team has us covered with inherited widgets.
To get started, we need to create a widget that extends InheritedWidget.
class MyInheritedWidget extends InheritedWidget {
@override
const MyInheritedWidget({
super.key,
required super.child,
});
@override
bool updateShouldNotify(MyInheritedWidget oldWidget) {
return true;
}
static MyInheritedWidget? of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<MyInheritedWidget>();
}
}
This boilerplate code includes everything we need to get started, but on its own it is not very helpful. Let us deconstruct what is going on, then figure out how to make it useful to us.
child parameter. Since we are extending the base class, we will need to override the constructor, as we have done before.updateShouldNotify method of the InheritedWidget. This will ensure that if any values are updated inside our inherited widget, all its children will be aware that those values have changed.Before we look at Lines 14-16, let us look at how to use our new widget. To relate it back to our earlier example, we will also modify it to add a text parameter.
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(
body: MyInheritedWidget(
text: "Hello, Flutter!",
child: MyWidget(),
),
),
);
}
}
class MyInheritedWidget extends InheritedWidget {
final String text;
@override
const MyInheritedWidget({
super.key,
required this.text,
required super.child,
});
@override
bool updateShouldNotify(MyInheritedWidget oldWidget) {
return oldWidget.text != text;
}
static MyInheritedWidget? of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<MyInheritedWidget>();
}
}
class MyWidget extends StatelessWidget {
const MyWidget({super.key});
@override
Widget build(BuildContext context) {
final inheritedWidget =
context.dependOnInheritedWidgetOfExactType<MyInheritedWidget>();
final String text = inheritedWidget!.text;
return Text(text);
}
}
Companion code: in Example 4.24, updateShouldNotify returns true, so the widgets that depend on MyInheritedWidget are notified whenever it is rebuilt with a new instance; the book's oldWidget.text != text notifies them only when text changes.
You will notice that we added the parameter on Line 18 and made it a required parameter on Line 23. Then, on Line 9, we passed some text into the inherited widget. To print the text on line 46, we first need to locate our inherited widget (Lines 42 and 43), and then we get the value of text on Line 44.
It is Line 43 that we want to focus on, though. That is an awfully cumbersome amount of code to type just to refer to our inherited widget! Would it not be great if we could just call it by name? It turns out, we can! That is where Lines 32-34 come into play (or Lines 14-16 in our old example). This specifies an of() method for our inherited widget, which simply returns the long, cumbersome line. It only requires passing in a BuildContext to function, too. Now when we want to search for our inherited widget, we can do it by name!
class MyWidget extends StatelessWidget {
const MyWidget({super.key});
@override
Widget build(BuildContext context) {
final inheritedWidget = MyInheritedWidget.of(context);
final String text = inheritedWidget!.text;
return Text(text);
}
}
Runnable copy: examples/flutter_for_jobseekers_ch04/lib/inherited/my_inherited_widget.dart (with MyWidget using MyInheritedWidget.of(context))
Inherited widgets in Flutter itself
Flutter uses inherited widgets in several ways, right out of the box. Three of the biggest ways it is used are with Theme, MediaQuery, and Navigator. We are going to use all three of these inherited widgets throughout this book, so keep an eye out for them.
Theme
Theme as an inherited widget that contains all sorts of styling properties that can be used to change the look and feel of widgets throughout the application. The MaterialApp and CupertinoApp widgets both accept a theme parameter, which they use to cascade down the styling properties.Navigator
Navigator is used to route the user to different parts of the application.MediaQuery
For example, we could use MediaQuery to create a SizedBox whose width is precisely half its parent:
SizedBox(
width: MediaQuery.of(context).size.width / 2,
)
Inherited widgets are some of the most useful widgets available in the whole toolkit due to their unique ability to allow us to access their data via the BuildContext of any other widget. However, it is not fair to keep bringing up BuildContext without explaining what it is, so let us investigate that now.
Introduction to BuildContext
In Flutter, we often like to think of everything as a widget. While this is not strictly true, it is also not far from the truth. What is more, each widget ends up in the widget tree, as we have discussed earlier in this chapter. How does any widget know what its place is in the widget tree? How does it know who its parent is, or what its constraints are? This is what BuildContext is for.
BuildContext contains information about where a widget is in the widget tree. But how does it do this?We learned earlier about the widget tree, but as we touched upon briefly earlier, that is not the only tree that Flutter creates. Let us go back to our example from the beginning of the chapter to figure this all out:
Container(
color: Colors.lightBlue,
child: Row(
children: const [
Image(
image: NetworkImage(
'https://flutter.github.io/assets-for-api-docs/assets/widgets/owl.jpg'),
),
Text('Flutter is fun!'),
],
),
)
This is the widget tree which adds some text next to a picture of an owl. The widget tree this creates will look like figure 4.17:

Figure 4.17: Our example widget tree.
Under the hood, Flutter uses these widgets as a blueprint to create an element tree (figure 4.18).

Figure 4.18: How the widget tree maps to the element tree.
For each widget created in the widget tree, Flutter creates a corresponding element in the element tree. These elements are eventually used to create a render tree, which is what Flutter uses to composite and draw the widgets to the screen using Skia or Impeller, which is slated to replace Skia, and may well have by the time this book makes it into readers' hands (see figure 4.19).
Skia
Impeller
Elements on the element tree have an associated state object if the element is a StatefulElement. When Flutter detects that the state of an element has changed, it will mark the corresponding widget as needing to be updated, causing it to become unmounted from the widget tree and replaced by a new widget, which is associated with the same element.
In the case that a stateful widget's state is changed, the state of the element is updated. When that occurs, the old widget is unmounted, and a new widget is mounted in its place. The element, and thus its state, never gets removed from the element tree — only the widget is replaced.

Figure 4.19: How all three trees relate.
This is where BuildContext comes in. Every element in the element tree — stateful elements and stateless elements — are extended from the base Element class. And what is an Element?
abstract class Element extends DiagnosticableTree implements BuildContext
BuildContext. So, any time you refer to BuildContext, you are referencing an element in the element tree.Conclusion
In this chapter, we covered the three different types of widgets, including the widget lifecycle and how they are drawn to the screen. We also discussed how Flutter uses the widgets to create a widget tree, and then uses the widget tree to create an element tree and a render tree.
In the upcoming chapter, we are going to learn all about buttons, text fields, and other ways of collecting input from users. Before we do that, take a minute to congratulate yourself! These first four chapters have been densely packed with some very technical details. You have done well to make it this far, and if there is anything you need to review, the pages will always be here for you.
Questions
- What design paradigm does Flutter use?
- What method is called for each widget when Flutter wants to draw a widget to the screen?
- What are three ways you can determine what properties are available for a widget?
- What is the difference between a positional parameter and a named parameter?
- When creating a widget, how do you specify that a parameter is either positional or named?
- What does the question mark after a type confer?
- When would you need to use a
Key? - What is a private object and how is one defined?
- What is the lifecycle of a stateful widget?
- What is the difference between a stateless and a stateful widget?
- What is the purpose of an inherited widget? What is an example of one?
- What is
BuildContext?
Key terms
Element, which each element in the element tree is based on.Theme, MediaQuery, and Navigator.State object, allowing for the widget to be changed and updated after it has been rendered to the screen. Stateful widgets are often used to add interactivity (for example, with a Button, Radio, Checkbox, and so on) but may also include things which perform background operations (such as fetching an image from the internet and displaying it once it has loaded).Row, Column, Container, Text, and Center, although there are many, many more available to choose from.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.-a). Introduction to Dart. Retrieved from Dart: https://dart.dev/language (added, not in the book)
- Dart. (n.d.-b). Operators. Retrieved from Dart: https://dart.dev/language/operators (added, not in the book)
- Flutter. (2021, December 6). Material 3 Update TextTheme to have M3 names for styles (#93725). Retrieved from GitHub: https://github.com/flutter/flutter/pull/93725 (added, not in the book)
- Flutter. (2024, March 28). Remove deprecated
TextThememembers (#139255). Retrieved from GitHub: https://github.com/flutter/flutter/pull/139255 (added, not in the book) - Flutter. (n.d.-a). Impeller rendering engine. Retrieved from Flutter: https://docs.flutter.dev/perf/impeller (added, not in the book)
- Flutter. (n.d.-b). InheritedWidget class. Retrieved from Flutter API: https://api.flutter.dev/flutter/widgets/InheritedWidget-class.html (added, not in the book)
- Flutter. (n.d.-c). TextField class. Retrieved from Flutter API: https://api.flutter.dev/flutter/material/TextField-class.html (added, not in the book)
- Flutter. (n.d.-d). Building user interfaces with Flutter. Retrieved from Flutter: https://docs.flutter.dev/ui (added, not in the book)
Installing Flutter and Configuring Your IDE
Set up Flutter on Windows or macOS with Git, Android Studio and an Android Virtual Device, configure Visual Studio Code, and run your first app.
Handling User Input
Buttons, text fields, pickers, radios, checkboxes, switches and sliders in Material and Cupertino, plus validating and submitting input with a Form.