skip to Main Content

I want to find out the color of AppBar text:

import 'package:flutter/material.dart';

void main() => runApp(const MaterialApp(
      home: MyHomePage(),
    ));

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    print(Theme.of(context).appBarTheme.foregroundColor); // null
    print(Theme.of(context)
        .colorScheme
        .onPrimary); // Color(0xffffffff) - wrong: text is black not white
    return const Scaffold(
      body: Text('ok'),
    );
  }
}

What should I do?

2

Answers


  1. When we dont provide any theme data for appBarTheme, it will use textTheme.titleLarge by default to get the color use

    Theme.of(context).textTheme.titleLarge?.color;
    

    As titleTextStyle documented as follows

    If this property is null, then [AppBarTheme.titleTextStyle] of [ThemeData.appBarTheme] is used.

    If that is also null, the default value is a copy of the overall theme’s [TextTheme.titleLarge] [TextStyle], with color set to the app bar’s [foregroundColor].

    Login or Signup to reply.
  2. Sure, the Theme.of(context) gives you access to the current theme in your widget tree. However, in the case of the AppBar text color, it’s inherited from the AppBarTheme or TextTheme within the theme.

    To retrieve the text color of the AppBar, you should access the textTheme property within the AppBarTheme:

    import 'package:flutter/material.dart';
    
    void main() => runApp(const MaterialApp(
          home: MyHomePage(),
        ));
    
    class MyHomePage extends StatelessWidget {
      const MyHomePage({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        final appBarTheme = Theme.of(context).appBarTheme;
        final appBarTextTheme = appBarTheme.textTheme;
        final appBarTextColor = appBarTextTheme?.headline6?.color;
    
        print(appBarTextColor); // This will print the color of AppBar text
    
        print(Theme.of(context).colorScheme.onPrimary); // This is the primary color, not AppBar text color
    
        return const Scaffold(
          body: Text('ok'),
        );
      }
    }
    

    This code fetches the AppBar‘s textTheme and then retrieves the color from the headline6, which typically corresponds to the text style used in the AppBar title. The appBarTextColor will represent the color of the AppBar text.

    Remember, if the headline6 is not specified or if it’s inherited from another source, accessing its color directly might return null, so make sure to handle such cases gracefully in your code.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search