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
When we dont provide any theme data for
appBarTheme
, it will usetextTheme.titleLarge
by default to get the color useAs
titleTextStyle
documented as followsSure, the
Theme.of(context)
gives you access to the current theme in your widget tree. However, in the case of theAppBar
text color, it’s inherited from theAppBarTheme
orTextTheme
within the theme.To retrieve the text color of the
AppBar
, you should access thetextTheme
property within theAppBarTheme
:This code fetches the
AppBar
‘stextTheme
and then retrieves the color from theheadline6
, which typically corresponds to the text style used in theAppBar
title. TheappBarTextColor
will represent the color of theAppBar
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.