4

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),
          )
       ),
     ),
   );
 }
}
Ravindra S. Patil
  • 11,757
  • 3
  • 13
  • 40

3 Answers3

3

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'),
),
Ravindra S. Patil
  • 11,757
  • 3
  • 13
  • 40
  • Oh, so if onPressed: null, then you have to use MaterialStateProperty.all. Is this because Flutter treats null state buttons different from elevated buttons? Because I can see that when you use ElevatedButton.styleFrom, the onPressed is not null, but an empty function. – yerdeth Apr 15 '23 at 22:32
0

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'),
                )
0
ElevatedButton(
              style: ElevatedButton.styleFrom(
                primary: Colors.blueAccent,
              ),
              onPressed: () {},
              child: const Text(
                "Button",
                style: TextStyle(
                  color: Colors.white,
                ),
              ),
            ),
Nazmul Hasan
  • 175
  • 2
  • 12