How do I set a standard elevated button theme in Flutter 3.16?

743 Views Asked by At

It looks like when I upgraded from Flutter 3.10 to 3.16, they are now using something called material 3 to define standard for Flutter elements. This changed the entire look of my app. I don't want to just set useMaterial3 to false because Flutter recommends to use this for new work. How do I quickly override the standard ElevatedButton theme to give it the look I want everywhere in my app? I know I can go to each button and change its style, but given how far I am in the project that would take way too long.

1

There are 1 best solutions below

2
On BEST ANSWER

You can override the default theme for ElevatedButtons by setting up a custom theme for your app. Here's an example of how you can do it:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // Override the default theme for ElevatedButton
    final ThemeData theme = ThemeData.light().copyWith(
      elevatedButtonTheme: ElevatedButtonThemeData(
        style: ButtonStyle(
          backgroundColor: MaterialStateProperty.all(Colors.blue), // Set your desired background color
          textStyle: MaterialStateProperty.all(TextStyle(color: Colors.white)), // Set your desired text color
          // Add more customizations as needed
        ),
      ),
    );

    return MaterialApp(
      title: 'My App',
      theme: theme,
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('My App'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            // Your button action
          },
          child: Text('Custom ElevatedButton'),
        ),
      ),
    );
  }
}

In this example, elevatedButtonTheme within the ThemeData allows you to override the default style for all ElevatedButtons in your app. Adjust the properties under ButtonStyle to customize the look of the ElevatedButton as you desire.