【问题标题】:Set fontFamily for all buttons in Flutter为 Flutter 中的所有按钮设置 fontFamily
【发布时间】:2018-09-30 10:13:10
【问题描述】:

有没有办法为 Flutter 应用中的所有按钮设置 fontFamily?

我知道我可以使用 theme.fontFamily 为我的 MaterialApp 设置我的 fontFamily,但我想为我的所有按钮使用不同的 fontFamily。

我看到还有一个ButtonThemeData,但它似乎只与颜色和形状有关。

我不想每次使用按钮或必须包装所有类型的按钮时都明确设置我的 fontFamily,有什么办法可以做到这一点?

谢谢!

【问题讨论】:

    标签: flutter


    【解决方案1】:

    您应该使用主题来自定义整个小部件的字体,包括按钮:https://flutter.dev/docs/cookbook/design/fonts

    【讨论】:

      【解决方案2】:

      最简单的可能是创建一个帮助方法,该方法返回一个您希望配置的 Button。

      【讨论】:

        【解决方案3】:

        我建议创建一个“扩展”Flutter MaterialButton 或 RawMaterialButton 的自定义按钮。如果您希望按钮可重用,请记住将 buttonText 添加为参数。还记得在 Text 小部件样式中添加 TextStyle(fontFamily: 'Raleway')

        另一种选择是以与下面的按钮示例相同的方式“扩展” Flutter Text 小部件,并将您的 CustomTextWidget 作为子级添加到 Flutter MaterialButton 小部件。我更喜欢两者结合使用。 CustomButton 和 CustomText 小部件。

        import 'package:flutter/material.dart';
        
        class CustomButton extends StatelessWidget {
          CustomButton({@required this.onPressed});
          final GestureTapCallback onPressed;
        
          @override
          Widget build(BuildContext context) {
            return RawMaterialButton(
              fillColor: Colors.green,
              splashColor: Colors.greenAccent,
              child: Padding(
                padding: EdgeInsets.all(10.0),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: const <Widget>[
                    Icon(
                      Icons.face,
                      color: Colors.amber,
                    ),
                    SizedBox(
                      width: 10.0,
                    ),
                    Text(
                      "Tap Me",
                      maxLines: 1,
                      style: TextStyle(color: Colors.white),
                    ),
                  ],
                ),
              ),
              onPressed: onPressed,
              shape: const StadiumBorder(),
            );
          }
        }
        

        这里是实现:

        CustomButton(
             onPressed: () {
               print("Tapped Me");
             },
        )
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-08-08
          • 1970-01-01
          • 2023-03-30
          • 1970-01-01
          • 1970-01-01
          • 2011-03-27
          • 2017-04-03
          相关资源
          最近更新 更多