Flutter 分配主题文本样式

Bli*_*Dev 4 text themes simplify flutter

我想知道是否有比这种方法更好的方法将主题的某种默认文本样式分配给文本小部件。

Text(
 'Hello world',
  style: Theme.of(context).textTheme.headline1,
),
Run Code Online (Sandbox Code Playgroud)

我确实认为应该有一个单独的小部件或文本方法 Text.headline1 或简单的样式命令样式:TextStyle.headline1。

但似乎我必须通过 Theme.of(context) 才能得到这个。

有人有更好的解决方案吗?

小智 6

我认为你无法逃脱一些样板文件。对我来说这种方法看起来最干净

import 'package:flutter/material.dart';

class StyledText extends StatelessWidget {
  final String text;
  late final TextStyle? Function(BuildContext context)? getStyle;

  StyledText.headline1(this.text, {Key? key}) : super(key: key) {
    getStyle = (context) {
      return Theme.of(context).textTheme.headline1;
    };
  }

  StyledText.headline2(this.text, {Key? key}) : super(key: key) {
    getStyle = (context) {
      return Theme.of(context).textTheme.headline2;
    };
  }

  // ...

  @override
  Widget build(BuildContext context) {
    return Text(text, style: getStyle?.call(context));
  }
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用小部件

 StyledText.headline1("Hello world");
  
Run Code Online (Sandbox Code Playgroud)