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

如何在Flutter的ExpansionTile标题及Text组件中展示动态内容

问题原因与修复方案

核心问题点

  • 你编写的showindex函数没有显式返回值,ExpansionTile的title属性拿到的是空值,自然无法显示对应内容
  • 如果修改index变量后没有调用setState方法,Flutter UI不会触发重新渲染,也看不到更新后的标题

修复步骤

1. 修正showindex函数

给函数加上返回值声明和return关键字:

// 指定返回值为Widget类型,每个分支都返回对应Text组件
Widget showindex(int index) {
  if (index == 1) {
    return Text(amharicWords[index]);
  } else {
    return Text(EnglishWords[index]);
  }
}

2. 修正index更新逻辑

修改index值的代码必须放在setState回调里,才能触发UI重绘:

// 按钮点击的回调方法示例
onPressed: () {
  setState(() {
    // 在这里写修改index的逻辑,比如 index = 0; 或者 index = 1;
    index = 你的新index值;
  });
}

可选优化

你也可以直接在title属性里写判断逻辑,不用单独封装函数,代码更简洁:

ExpansionTile(
  leading: Icon(Icons.text_fields),
  title: index == 1 ? Text(amharicWords[index]) : Text(EnglishWords[index]),
  subtitle: Text("amahric words"),
  children: <Widget>[
    Container(
      width: 340,
      height: 45,
      color: Colors.purple,
      child: Padding(
        padding: const EdgeInsets.fromLTRB(50, 10, 0, 0),
        child: Text(
          GeezWords[index],
          style: TextStyle(fontSize: 20),
        ),
      ),
    ),
  ],
),

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 13:21:02