【问题标题】:RaisedButton's background color does not change after setting ThemeData's primaryswatch property设置 ThemeData 的 primaryswatch 属性后 RaisedButton 的背景颜色不会改变
【发布时间】:2020-01-05 11:49:06
【问题描述】:

下面是一个带有 RaisedButton 的干净 Flutter 示例。

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton(
              child: Text('test'),
              onPressed: () {},
            )
          ],
        ),
      ),
    );
  }
}

来自 theme_data.dart 的片段

// Used as the default color (fill color) for RaisedButtons. Computing the
// default for ButtonThemeData for the sake of backwards compatibility.
buttonColor ??= isDark ? primarySwatch[600] : Colors.grey[300];

material_button.dart 中的片段

/// The button's fill color, displayed by its [Material], while it
/// is in its default (unpressed, [enabled]) state.
///
/// The default fill color is the theme's button color, [ThemeData.buttonColor].
///
/// See also:
///
///  * [disabledColor] - the fill color of the button when the button is disabled.
final Color color;

基于上述,我假设 RaisedButton 的背景颜色为蓝色,因为 buttonColor 将从 primarySwatch 推断出来。相反,RaisedButton 的背景颜色为灰色。 我知道我可以直接通过 ThemeData 设置 buttonColor 参数,但由于源代码声明 buttonColor 将从 primarySwatch 推断,我只是好奇为什么它不起作用。我错过了什么?

【问题讨论】:

标签: flutter


【解决方案1】:

您的答案在您引用的代码中:

buttonColor ??= isDark ? primarySwatch[600] : Colors.grey[300];

在同一个文件 (theme_data.dart) 上,您可以看到 isDark 定义为:

final bool isDark = brightness == Brightness.dark;

由于您的主题未定义为Brightness.dark,因此按钮将默认为Colors.grey[300]

【讨论】:

  • 很高兴我能帮上忙。祝你好运!
猜你喜欢
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
  • 2022-06-11
  • 2014-06-21
  • 2014-04-21
  • 2021-01-23
  • 2011-06-15
  • 1970-01-01
相关资源
最近更新 更多