Search code examples
fluttercolors

How to determine text color in flutter?


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?


Solution

  • When we don't 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].