skip to Main Content

I want to have an Widget that expands the functionality of an existing Widget.
Example: I want an "ResponisveText"-Widget. It should have the exact same properties as the existing Text-Widget but with the difference that the fontSize is handled different here.

How can I create such an Widget in an clean way, so that I have access to the fontSize etc.?

Before, I did it like this, but I think there’s a better way:

Text('foo', style: Font.body1.copyWith(fontSize: responsiveFontSize(Font.body1.fontSize))

I want It to be like this:

ResponsiveText('foo', style: Font.body1)

2

Answers


  1. That would be my solution:

    class ResponsiveText extends StatelessWidget {
           ResponsiveText({super.key, required this.textToDisplay});
           final String textToDisplay;
        
          final List fonts = [];
    
      @override
      Widget build(BuildContext context) {
        fonts.addAll([
          Theme.of(context).textTheme.headline1,
          Theme.of(context).textTheme.headline2,
          Theme.of(context).textTheme.headline3,
          Theme.of(context).textTheme.headline4,
          Theme.of(context).textTheme.headline5,
          Theme.of(context).textTheme.headline6,
          ]);
        return Text(textToDisplay, style: fonts[Random().nextInt(6)],);
      }
    }
    

    You utilize native headline (or other ThemeOfContext) parameters that you can modify by hand in the file that handles app ui.

    Login or Signup to reply.
  2. you can achieve what you want by extending the Text widget, and then instead of using directly the style property, you declare a new style parameter, that before assigning its value to the super.style parameter, you can manipulate your fontSize value as you wish.

    class ResponsiveText extends Text {
    
      ResponsiveText(
        super.data,
        {
          TextStyle? style,
          super.strutStyle,
          super.textAlign,
          super.textDirection,
          super.locale,
          super.softWrap,
          super.overflow,
          super.textScaleFactor,
          super.maxLines,
          super.semanticsLabel,
          super.textWidthBasis,
          super.textHeightBehavior,
          super.selectionColor,
        }
      ) : super(style: _handleFontSize(style));
    
      static TextStyle? _handleFontSize(TextStyle? style) {
        return style?.copyWith(
          fontSize: responsiveFontSize(style.fontSize)
        );
      }
    
      static double? responsiveFontSize(double? fontSize) {
        // do stuff here to your font size
        return fontSize;
      }
    }
    

    let me know if you have any question

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search