How to dynamically change the App Title in Flutter Web?

Issue

Web apps usually reflect the currently displayed content in the tab’s title.

Supplying the title parameter to a MaterialApp or WidgetsApp means that I cannot change it without rebuilding the entire tree, i.e. calling setState at the top level where I return my MaterialApp.

MaterialApp(
  title: 'Web app title',
  ...,
)

I want to be able to change the app title from anywhere in the app at any time. How do I do that?

Solution

Dynamic app title in Flutter

The app title can be dynamically changed on all platforms using SystemChrome.setApplicationSwitcherDescription:

@override
Widget build(BuildContext context) {
    SystemChrome.setApplicationSwitcherDescription(ApplicationSwitcherDescription(
      label: 'Dynamic web app title',
      primaryColor: Theme.of(context).primaryColor.value,
    ));


  return Container(...);
}

Screen capture

SystemChrome becomes available with import 'package:flutter/services.dart'; and you want to call setApplicationSwitcherDescription in your build method.

This is also how Title does it (see source code), which is the widget used by WidgetsApp, MaterialApp, etc.

Thus, you can also use a Title widget instead of accessing SystemChrome yourself:

@override
Widget build(Context context) {
  return Title(
    label: 'Dynamic app title',
    primaryColor: Theme.of(context).primaryColor,
    child: ..,
  );
}

label

The label parameter is pretty straight forward: it maps exactly to what title is in your MaterialApp and just a String.

primaryColor

The primaryColor will determine the color the system might use in the application switcher, e.g. the title bar color in recents on Android.
This is an int instead of a Color, which is why you need to call Color.value to convert your primary color to an integer.

Interference with other Titles

You might ask yourself if calling setApplicationSwitcherDescription or inserting a Title widget when the title property on MaterialApp is set can cause any problems.
The answer is: no because the widget that is the deepest down in the tree will set the title. Essentially, even if the whole app rebuilds, your setApplicationSwitcherDescription will be called after that of MaterialApp assuming you are calling it in a child and therefore you will override the MaterialApp title.

Answered By – creativecreatorormaybenot

Answer Checked By – Candace Johnson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *