Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way of using ThemeData copyWith in flutter MaterialApp widget?

I was trying to change the accentColor after copying the ThemeData.light(), then I have this sample screen with a FloatingActionButton

class Sample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () {},
        child: Icon(Icons.add),
      ),
     )}}

Then in the main widget in main.dart to call runApp, if I set the ThemeData for the MaterialApp widget like this, The FloatingActionButton will have a color of orange.

theme: ThemeData(
  accentColor: Colors.orange
)

but if I tried to inherit the color from the Themedata.light().copyWith, the FloatingActionButton will still have the color blue from the light theme.

theme: ThemeData.light().copyWith(
  accentColor: Colors.orange
)

I was expecting the FloatingActionButton should have the orange color, because It inherit the light theme and override the accentColor.

like image 511
zer09 Avatar asked May 20 '20 07:05

zer09


People also ask

How do you use copyWith in flutter?

Use copyWith to create a new object with the same properties as the original, but with some of the values changed. You can then apply these techniques with Freezed to make the process of creating and working with immutable structures easier.

How do you use ThemeData in flutter?

Applying the Theme: To override the default theme of a widget in Flutter one can wrap the same widget inside the Theme widget. A Themedata() instance can be created and passed to the respective widget as shown below: Dart.

What is ThemeData light?

ThemeData.light() A default light blue theme. This theme does not contain text geometry. Instead, it is expected that this theme is localized using text geometry using ThemeData.


1 Answers

this is a common problem in Flutter, but you can solve it for now by doing the following:

theme: ThemeData.light().copyWith(
    floatingActionButtonTheme:
        ThemeData.light().floatingActionButtonTheme.copyWith(
              backgroundColor: Colors.orange,
            ),
  ),

if you used any other button you should do the same and overwrite it's Theme,

you can read more about the problem here Updating the Material Buttons and their Themes

and buttonColor not honored when using ThemeData.light().copyWith()

like image 102
mohamed_ashraf51 Avatar answered Oct 17 '22 23:10

mohamed_ashraf51