Divyansh Rathi
Divyansh Rathi

Reputation: 55

flutter elevated button color not changing

I am not able to change the background of flutter button. please help.

the error that VS code shows is "Invalid constant value.", underlining the MaterialStateProperty.all(Colors.red) line

import 'package:flutter/material.dart';

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

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

// This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
  return const MaterialApp(
     home: Home(),
  );
  }
}

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

 @override
 Widget build(BuildContext context) {
   return Scaffold(
      appBar: AppBar(
      title: const Text('My first  Name'),
      centerTitle: true,
      backgroundColor: Colors.red[300],
      ),
     body: const Center(
       child: ElevatedButton(
          onPressed: null,
          child: Text('click me'),
          style: ButtonStyle(
             backgroundColor: MaterialStateProperty.all(Colors.red),
          )
       ),
     ),
   );
 }
}

Upvotes: 4

Views: 6559

Answers (3)

Ravindra S. Patil
Ravindra S. Patil

Reputation: 14775

Try below code hope its help to you. Remove const keyword

Center(
  child: ElevatedButton(
    onPressed: null,
    child: const Text('click me'),
    style: ButtonStyle(
      backgroundColor: MaterialStateProperty.all(Colors.red),
    ),
  ),
),

Other way:

ElevatedButton(
  onPressed: () {},
  style: ElevatedButton.styleFrom(
    backgroundColor: Colors.red,
  ),
  child: const Text('click me'),
),

Upvotes: 4

Nazmul Hasan
Nazmul Hasan

Reputation: 265

ElevatedButton(
              style: ElevatedButton.styleFrom(
                primary: Colors.blueAccent,
              ),
              onPressed: () {},
              child: const Text(
                "Button",
                style: TextStyle(
                  color: Colors.white,
                ),
              ),
            ),

Upvotes: 0

Ankit Kumar Maurya
Ankit Kumar Maurya

Reputation: 1207

May be this one help you

ElevatedButton(
                  style: ButtonStyle(
                      textStyle: MaterialStateProperty.all(TextStyle(
                          color: Colors.white,
                          backgroundColor: Colors.green))),
                  onPressed: () {
                    print('pressed');
                  },
                  child: Text('PRESS'),
                )

Upvotes: 0

Related Questions