首页 > 解决方案 > 当函数作为参数传递时,为什么按钮颜色会变为禁用按钮颜色?

问题描述

我遇到了最近对颤动按钮的更改,我正在使用提升按钮。当我将函数作为参数传递给要设置为高架按钮的 onTap 变量的值时,它的颜色会更改为禁用按钮颜色或当我们将 null 分配给 onTap 时使用的颜色,如下所示。

在此处输入图像描述

添加以下样式属性不会更改颜色:

style: ElevatedButton.styleFrom(
      primary: Colors.white,
      onPrimary: Colors.amberAccent,)

但是,如果我们使用 ButtonStyle() 方法,它会改变颜色:

style: ButtonStyle(
                      backgroundColor: MaterialStateProperty.all<Color>(Colors.white),
                    ),

在此处输入图像描述

  1. 当函数作为参数传递时,为什么颜色会变为禁用的按钮颜色?
  2. 为什么 ButtonStyle() 有效,而不是 ElevatedButton.styleFrom()?

这是代码:

 class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  int i = 0;

  updatePage(int value) {
    setState(() {
      i = value;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        MyButton(
          s: '10',
          f: updatePage(10),
        ),
        MyButton(
          s: '20',
          f: updatePage(20),
        ),
      ],
    );
  }
}

class MyButton extends StatelessWidget {
  final String s;
  final Function f;

  MyButton({this.s, this.f});

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 70,
      height: 40,
      child: ElevatedButton(
        child: Text(s),
        onPressed: f,
        style: ElevatedButton.styleFrom(
          primary: Colors.white,
        ),
      ),
    );
  }
}

谢谢你。

标签: flutterflutter-layoutmaterial-design

解决方案


你能提供更多信息吗?

我尝试运行以下代码,但看不到“禁用颜色”。您也可以尝试在dartpad上运行此代码 在此处输入图像描述

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  void foo() {
    print("hello world");
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SizedBox.expand(
          child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            ElevatedButton(
              style: ElevatedButton.styleFrom(
                primary: Colors.white,
                onPrimary: Colors.amberAccent,
              ),
              onPressed: foo,
              child: Text("Elevated Button 1"),
            ),
            ElevatedButton(
              style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all<Color>(Colors.white),
              ),
              onPressed: foo,
              child: Text("Elevated Button 2", style: TextStyle(color: Colors.amberAccent),),
            ),
          ],
        ),
        ),
      ),
    );
  }
}

推荐阅读