How to dynamically change the App Title in Flutter Web?

0

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

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More