Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter assign Theme text style

I was wondering is there is a better way to assign a certain default text style of my Theme to a Text widget than this approach.

Text(
 'Hello world',
  style: Theme.of(context).textTheme.headline1,
),

I did assume there should be something like a separate Widget or a Text Method Text.headline1 or simply a style Command style: TextStyle.headline1.

But seems I have to go through the Theme.of(context) to get this.

Does anyone have a better solution?

like image 828
Bliv_Dev Avatar asked Jul 21 '26 09:07

Bliv_Dev


2 Answers

I think yon can't escape some boilerplate. For me this approach looks cleanest

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

And use the widget like this

 StyledText.headline1("Hello world");
  
like image 155
Bonco Avatar answered Jul 23 '26 00:07

Bonco


Theme.of(context) is a great way to go for a variety of reasons, like switching between light and dark themes. I like to create a variable for the theme and text theme to keep things clean and efficient.

Widget build(BuildContext context) {
  final theme = Theme.of(context);
  final textTheme = theme.textTheme;

  return Column(
    children: [
      Text('Heading Text', style: textTheme.headline1),
      Text('Caption Text', style: textTheme.caption),
      Text('Body text...', style: textTheme.bodyText1),
    ],
  );
}
like image 24
Jared Cornwall Avatar answered Jul 22 '26 23:07

Jared Cornwall