Search code examples
fluttergradient

ShaderMask on Text gradient issue


I want to apply a gradient to text. Below is the code that works fine until I specify height: 1.

For some reason, shader doesn't apply to the bottom part of text (see black notch at the bottom of "y" letter).

I thought the problem was that height parameter affects the bounds.

But if I specify much larger values in shaderCallback, it doesn't affect the result.

Any ideas how to apply gradient to text even with any height values?

no height specified
enter image description here

height: 1
enter image description here

import 'package:flutter/material.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(body: Body()),
    );
  }
}

class Body extends StatelessWidget {
  const Body({super.key});

  @override
  Widget build(BuildContext context) {
    const style = TextStyle(
      fontSize: 48,
      fontWeight: FontWeight.bold,
      color: Colors.black,
      height: 1,
    );
    return Center(
      child: ShaderMask(
        blendMode: BlendMode.srcIn,
        shaderCallback: (bounds) => _gradient.createShader(bounds),
        child: const Text('Why?', style: style),
      ),
    );
  }
}

const _gradient = LinearGradient(colors: [Colors.red, Colors.red]);

Solution

  • You can use strutStyle instead the style only for the height.

    const Text(
              'Why?',
              style: style,
              strutStyle: StrutStyle(
                height: 1,
              ),
            ),
    

    More info about strutStyle: https://api.flutter.dev/flutter/painting/StrutStyle-class.html