David
David

Reputation: 3614

Set fontFamily for all buttons in Flutter

Is there a way to set the fontFamily for all buttons in a Flutter app?

I see I can set my fontFamily for my MaterialApp using theme.fontFamily, but I'd like to use a different fontFamily for all my buttons.

I saw there is also a ButtonThemeData, but it seems to be related to colors and shapes only.

I don't want to set my fontFamily explicitly every time I use a button or having to wrap all types of buttons, is there any way to accomplish this?

Thanks!

Upvotes: 4

Views: 2507

Answers (3)

Christer
Christer

Reputation: 3076

I recomend creating a custom button that "extends" Flutter MaterialButton or RawMaterialButton. Remember to add buttonText as a paramater too if you want your button to be reusable. Also remember to add TextStyle(fontFamily: 'Raleway') to the Text widget style.

Another option would be to "extend" the Flutter Text widget in the same way as with the button example below, and add your CustomTextWidget as a child to the Flutter MaterialButton widget. I prefer to use both in a combination. CustomButton together with CustomText widget.

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

Here is the implementation:

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

Upvotes: 0

AVEbrahimi
AVEbrahimi

Reputation: 19184

You should use themes to customize fonts for whole widgets, including buttons : https://flutter.dev/docs/cookbook/design/fonts

Upvotes: 1

Randal Schwartz
Randal Schwartz

Reputation: 44111

Simplest might be to create a helper method that returns a Button configured as you wish.

Upvotes: 0

Related Questions