You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何优雅扩展Widget功能:创建ResponsiveText组件

实现ResponsiveText组件的简洁方案

要实现完全复用Text组件所有属性、同时自动处理fontSize响应式逻辑的ResponsiveText,通过自定义StatelessWidget封装即可,具体实现如下:

1. 定义ResponsiveText组件

直接复制Text的所有参数,在build方法中自动处理style里的fontSize,保留原有样式的其他属性:

import 'package:flutter/material.dart';

class ResponsiveText extends StatelessWidget {
  final String data;
  final TextStyle? style;
  final TextAlign? textAlign;
  final TextOverflow? overflow;
  final int? maxLines;
  final StrutStyle? strutStyle;
  final TextDirection? textDirection;
  final Locale? locale;
  final bool? softWrap;
  final double? textScaleFactor;
  final String? semanticsLabel;
  final TextWidthBasis? textWidthBasis;
  final TextHeightBehavior? textHeightBehavior;

  const ResponsiveText(
    this.data, {
    super.key,
    this.style,
    this.textAlign,
    this.overflow,
    this.maxLines,
    this.strutStyle,
    this.textDirection,
    this.locale,
    this.softWrap,
    this.textScaleFactor,
    this.semanticsLabel,
    this.textWidthBasis,
    this.textHeightBehavior,
  });

  // 封装响应式字体大小计算逻辑
  double _getResponsiveFontSize(BuildContext context, double baseSize) {
    final screenWidth = MediaQuery.of(context).size.width;
    // 这里替换成你实际的响应式逻辑
    if (screenWidth < 360) return baseSize * 0.8;
    if (screenWidth > 600) return baseSize * 1.2;
    return baseSize;
  }

  @override
  Widget build(BuildContext context) {
    // 处理style:保留原有样式,替换fontSize为响应式值
    final baseFontSize = style?.fontSize ?? Theme.of(context).textTheme.bodyLarge?.fontSize ?? 16;
    final processedStyle = style?.copyWith(
      fontSize: _getResponsiveFontSize(context, baseFontSize),
    );

    return Text(
      data,
      style: processedStyle,
      textAlign: textAlign,
      overflow: overflow,
      maxLines: maxLines,
      strutStyle: strutStyle,
      textDirection: textDirection,
      locale: locale,
      softWrap: softWrap,
      textScaleFactor: textScaleFactor,
      semanticsLabel: semanticsLabel,
      textWidthBasis: textWidthBasis,
      textHeightBehavior: textHeightBehavior,
    );
  }

  // 对外暴露处理后的fontSize(可选)
  double getProcessedFontSize(BuildContext context) {
    final baseFontSize = style?.fontSize ?? Theme.of(context).textTheme.bodyLarge?.fontSize ?? 16;
    return _getResponsiveFontSize(context, baseFontSize);
  }
}

2. 使用方式

直接像原生Text组件一样调用,传入style后组件会自动处理fontSize:

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

3. 访问处理后的fontSize

如果需要获取最终的响应式字体大小,可调用组件的getProcessedFontSize方法:

final responsiveText = ResponsiveText('foo', style: Font.body1);
final processedSize = responsiveText.getProcessedFontSize(context);

内容的提问来源于stack exchange,提问作者Linus Grosser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 03:55:21