Error: no named parameter with the name 'color' Flutter

Error: no named parameter with the name 'color' Flutter

所以我是 Dart 和 Flutter 的新手,运行 遇到了一个问题。我正在尝试学习布局并对文本和按钮小部件进行细微的 UI 更改。我在这里尝试将 ElevatedButton 的颜色更改为 blue

import 'package:flutter/material.dart';

class Answer extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      child: ElevatedButton(
        color: Colors.blue,
        child: Text('Answer 1'),
        onPressed: null,
      ),
    );
  }
} 

当我 运行 代码时,我得到这个错误:

Error: no named parameter with the name 'color'

我认为使用按钮可以更改颜色参数。正确的实施方式是什么?

ElevatedButton(
  style: ElevatedButton.styleFrom({
    Color primary, // set the background color 
    Color onPrimary,  // foreground
  }),
),

您可以使用 styleFrom

设置 ElevatedButton 的样式
ElevatedButton(
      child: const Text('Button'),
      onPressed: () {},
      style: ElevatedButton.styleFrom(
          primary: Colors.purple,
    ),

或者您可以使用 ButtonStyle class

ElevatedButton(
      child: const Text('Button'),
      onPressed: () {},
      style: ButtonStyle(
          backgroundColor: MaterialStateProperty.all(Colors.red),
    ),

在 Flutter 中,一些 widget 处理用于一般应用主题目的的样式和主题,因此它不允许直接更改颜色,但带有样式参数:

ElevatedButton(
  style: ElevatedButton.styleFrom({
    Color primary: Colors.green,
    Color onPrimary: Colors.white,  
  }),
),

有关详细信息,请访问 Flutter documents ElevatedButton.styeFrom 并尝试使用不同的参数。

欢迎使用 Flutter。

您可以通过以下方式设置 ElevatedButton 的样式:

ElevatedButton(
       style: ButtonStyle(
             backgroundColor: MaterialStateProperty
             .all<Color>(Colors.blue),
             foregroundColor: MaterialStateProperty
            .all<Color>(Colors.white),
        ),
      child: Text('your text'),
      onPressed: null,
),