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

Flutter 使用ListTile实现书籍章节与索引列表相关问题求助

Flutter ListTile列表实现问题修复方案

1. 音频章节页章节名称展示异常修复

问题原因

  • 代码中直接对整个items列表调用toString()输出,没有通过itemBuilder传入的index取对应位置的章节数据
  • itemCount写死为3,后续新增章节时需要手动修改,扩展性差

修复后代码

class Item {
  final String name;
  Item({required this.name});
}

class Main_Audio_Page extends StatelessWidget {
  final List<Item> items = [
    Item(name: "Chapter 1"),
    Item(name: "Chapter 2"),
    Item(name: "Chapter 3"), // 后续新增章节无需修改其他代码
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Chapters'),
      ),
      body: ListView.builder(
        padding: const EdgeInsets.all(8),
        itemCount: items.length, // 动态取列表长度适配数据变化
        itemBuilder: (BuildContext context, int index) {
          return ListTile(
            title: Text(items[index].name), // 按索引取对应Item的name属性
            trailing: Icon(Icons.play_arrow),
            onTap: () {},
          );
        },
      ),
    );
  }
}

2. 书籍索引页运行报错修复

问题原因

Dart中列表下标从0开始,ListView.separated的itemBuilder传入的index最大值为items.length - 1,代码中使用items[index+1]会在渲染最后一项时出现下标越界错误。

如果你的需求是让索引从1开始展示,只需要修改展示的文本内容,不要修改访问列表的下标。

修复后代码

class Main_Index_Page extends StatelessWidget {
  Main_Index_Page({Key? key}) : super(key: key);

  final items = List<String>.generate(115, (i) => "index $i");

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Index Example'),
      ),
      body: ListView.separated(
        padding: const EdgeInsets.all(8),
        itemCount: items.length,
        itemBuilder: (BuildContext context, int index) {
          return ListTile(
            // 若要展示从1开始的索引,可改为 Text('index ${index+1}')
            title: Text(items[index]), 
          );
        },
        separatorBuilder: (BuildContext context, int index) => const Divider(),
      ),
    );
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 23:39:04