Apply ButtonStyle Properties to All Buttons Globally

Issue

I’ve implemented several long ListViews containing ElevatedButtons in my flutter project, and would now like to apply various ButtonStyle properties to all of them. I am certain there is a way to avoid applying these properties to each button individually, but haven’t been able to find anything in the Flutter docs or on Stack Overflow. Can this task be done globally?

Currently buttons have basic styling:

            ElevatedButton(
                style: const ButtonStyle(),
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => authorA()),
                  );
                },
                child: const Text("Author A")),
            ElevatedButton(
                style: const ButtonStyle(),
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => AuthorB()),
                  );
                },
                child: const Text("Author B")),
            ElevatedButton(
                style: const ButtonStyle(),
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => AuthorC()),
                  );
                },
                child: const Text("Author C)")),

My ListView contains hundreds of these buttons, and there are several other long ListViews containing buttons that I would like to style as well. what if I wanted to modify the ButtonStyle() property for all of them like below:

            ElevatedButton(
                style:   ButtonStyle(
                  backgroundColor: MaterialStateProperty.all<Color>(Colors.green),
                ),
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => AuthorA()),
                  );
                },
                child: const Text("Author A")),

Solution

Use theme or darkTheme property of MaterialApp to set global styles.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        elevatedButtonTheme: ElevatedButtonThemeData(
          style: ElevatedButton.styleFrom(
            primary: Colors.green,
          ),
        ),
      ),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

Answered By – p2kr

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.