Home > Back-end >  Flutter TabBar wrong labelColor when use ThemeData
Flutter TabBar wrong labelColor when use ThemeData

Time:12-11

I try to change labelColor value for TabBar via ThemeData.

child: MaterialApp(
        theme: ThemeData.light().copyWith(
          colorScheme: ColorScheme.fromSwatch(
            primarySwatch: Colors.deepPurple,
          ).copyWith(
            secondary: Colors.amber,
          ),
          tabBarTheme: ThemeData.light().tabBarTheme.copyWith(
                labelColor: ThemeData.light().colorScheme.secondary,
              ),
        ),
        home: const RootContainer(),),);

So my tabs should have shade of amber color. Instead they are some blue ... (picture below). What I'm doing wrong and how to fix it ?

Result: enter image description here

CodePudding user response:

The color doesn't change because the ThemeData.light() returns ThemeData that is not initilized. For using the color of the theme, wrap your widget by Builder with Theme.of(context) like below.

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.light().copyWith(
        colorScheme: ColorScheme.fromSwatch(
          primarySwatch: Colors.deepPurple,
        ).copyWith(
          secondary: Colors.amber,
        ),
      ),
      home: Builder(builder: (context) {
        final theme = Theme.of(context);
        
        return Theme(
          data: theme.copyWith(
            tabBarTheme: theme.tabBarTheme.copyWith(
              labelColor: theme.colorScheme.secondary,
            ),
          ),
          child: const RootContainer(),
        );
      }),
    );
  }
}
  • Related