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

如何在应用中展示API返回的错误?用Text Widget连续展示多错误方法

API错误信息展示及Flutter Text Widget多错误实现方案

一、应用内展示API错误的通用思路

  • 先解析后端返回的JSON结构,提取字段对应的错误列表
  • 根据场景选择展示方式:
    • 字段级提示:在对应输入框下方展示该字段的错误,帮助用户快速定位问题
    • 全局提示:通用类错误(非字段专属)可通过Toast、SnackBar或顶部弹窗展示
    • 批量汇总:将所有字段错误整理后,在页面顶部或专属错误区域统一列出

二、Flutter中用Text Widget连续展示多条错误信息

假设已将后端返回的JSON解析为如下Map结构:

Map<String, dynamic> errorResponse = {
  "message": {
    "mobile": ["手机号字段格式无效", "手机号字段至少需包含11位数字"]
  }
};

方式1:字符串拼接直接展示

提取目标字段的错误列表,用换行符或自定义分隔符拼接成单个字符串,传入Text Widget:

// 提取手机号对应的错误列表
List<String> mobileErrors = List<String>.from(errorResponse['message']['mobile']);
// 用换行符拼接多条错误
String combinedError = mobileErrors.join('\n');

// 在界面中使用
Text(combinedError, style: TextStyle(color: Colors.red, fontSize: 14));

方式2:RichText实现带样式的连续展示

如果需要给每条错误添加前缀(如圆点)或差异化样式,可使用RichText组合TextSpan:

List<String> mobileErrors = List<String>.from(errorResponse['message']['mobile']);

TextSpan buildErrorTextSpan() {
  TextSpan resultSpan = const TextSpan();
  for (int i = 0; i < mobileErrors.length; i++) {
    resultSpan = TextSpan(
      children: [
        resultSpan,
        TextSpan(
          text: '• ${mobileErrors[i]}',
          style: const TextStyle(color: Colors.red, fontSize: 14),
        ),
        // 最后一条错误不加换行
        if (i != mobileErrors.length - 1) const TextSpan(text: '\n'),
      ],
    );
  }
  return resultSpan;
}

// 调用RichText展示
RichText(text: buildErrorTextSpan());

方式3:Wrap+Text组合(可选)

若希望每条错误独立且自动适配换行,可使用Wrap组件包裹多个Text:

List<String> mobileErrors = List<String>.from(errorResponse['message']['mobile']);

Wrap(
  direction: Axis.vertical,
  spacing: 6, // 错误行之间的间距
  children: mobileErrors.map((error) => Text(
    '• $error',
    style: const TextStyle(color: Colors.red),
  )).toList(),
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 11:35:18