Flutter:定义自定义TextStyles以在整个应用程序中使用

Fra*_*per 5 flutter

如何定义一小组自定义TextStyles,然后可以在我的应用程序中重复使用.自定义TextStyles应基于主题中定义的TextStyles.

我知道如何创建单独的TextStyles(例如)

Theme.of(context).textTheme.title.copyWith(fontWeight: FontWeight.bold,)
Run Code Online (Sandbox Code Playgroud)

Col*_*son 7

您可以创建一个提供获取字体样式的方法的类.

这是一个声明一个CustomTextStyle类,它display5为一个非常大的文本公开一个方法的例子.

在此输入图像描述

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new HomePage(),
    );
  }
}

class CustomTextStyle {
  static TextStyle display5(BuildContext context) {
    return Theme.of(context).textTheme.display4.copyWith(fontSize: 192.0);
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) => new Scaffold(
    appBar: new AppBar(
      title: new Text('Custom Font Example'),
    ),
    body: new Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        new Card(
          child: new Container(
            child: new Text(
              'Wow',
              style: CustomTextStyle.display5(context),
            ),
          ),
        ),
      ],
    ),
  );
}
Run Code Online (Sandbox Code Playgroud)

  • 如果只适合全部一行,我只会使用=> (2认同)