Setting Dynamic Page Titles in Flutter Web

3 min read

Shaikh Afroz Avatar

Shaikh Afroz

Mobile Engineer

#flutter #web #dynamic-titles
Hero Image

Whenever you create a flutter web app the main title comes from what you define in the Material App ,

main.dart
MaterialApp(
title: 'My App', // This is from where it gets picket up
color: Colors.red,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomeScreen(),
);

in the above case it would be My App, but if you want to have different titles for different screens there are some solutions that you could use

Using Title Widget

The title widget is a straight forward solution, where in you just wrap the Page with Title widget and it works out of the box

some_page.dart
Title(
color: Colors.black,
title: 'Flutter New Title',
child: SomeOtherWidget(),
);

This is a very simple solution and works out of the box, but if you want to have a more dynamic solution you can use the SystemChrome class to set the title of the app, this is a more dynamic solution and can be used in a more complex app where you have a lot of screens and you want to set the title of the app based on the screen that is being displayed.

Using SystemChrome

utilities.dart
void setTitle(String title) {
SystemChrome.setApplicationSwitcherDescription(
ApplicationSwitcherDescription(
label: title,
primaryColor: Colors.black, // Color is required
),
);
}

Alternatively you can also create a Singleton or a service that handles the same for you if you have a very big flutter web apps

title_manager.dart
class TitleManager {
// Private constructor to prevent instantiation
TitleManager._();
/// Sets the application title for web.
static Future<void> setAppTitle([String? title]) async {
// Using microtask to ensure the title is updated without blocking other tasks.
Future.microtask(() {
SystemChrome.setApplicationSwitcherDescription(
ApplicationSwitcherDescription(
label: '$title | My App',
primaryColor: Theme.of(
rootNavigatorKey.currentContext as BuildContext
).colorScheme.primary.value, // Retrieves the app's primary color
),
);
});
}
}
Afroz