颤动升高的按钮颜色不变

flutter elevated button color not changing

我无法更改 flutter 按钮的背景。请帮忙

VS 代码显示的错误是“无效常量值。”,强调 MaterialStateProperty.all(Colors.red)

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),
          )
       ),
     ),
   );
 }
}

试试下面的代码希望对你有帮助。删除 const 关键字

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

其他方式:

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

这个可能对你有帮助

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