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

Flutter如何从第19位索引开始生成子列表集合?

问题分析与解决方案

核心问题

你的代码无法从第19位索引开始拆分列表,原因如下:

  1. 直接调用bytes.slices(chunkSize)会从列表起始索引0开始分割,未跳过前19个元素。
  2. 函数中的for循环完全无效——第一次迭代就直接返回结果,没有执行任何切片调整逻辑。
    另外,写入子列表的代码存在参数错误:你传入了整个列表chun,而非当前迭代的子列表ch。

修正后的代码

1. 修正列表拆分逻辑(local()函数)

static Future<List> local() async {
    File textAsset = File('/storage/emulated/0/RPSApp/assets/bluetooth.txt');
    final text = await textAsset.readAsString();
    final bytes =
        text.split(',').map((s) => s.trim()).map((s) => int.parse(s)).toList();

    int chunkSize = 19;

    List<int> padTo(List<int> input, int count) {
      return [...input, ...List.filled(count - input.length, 255)];
    }

    List<int> padToChunksize(List<int> input) => padTo(input, chunkSize);
    List<List<int>> items;

    // 关键:先截取从索引19开始的子列表,再进行拆分
    final bytesFromIndex19 = bytes.sublist(19);
    items = bytesFromIndex19.slices(chunkSize).map(padToChunksize).toList();

    return items;
  }

2. 修正子列表写入逻辑

final chun = await Utils.local();
await Future.forEach(chun, (ch) async {
    await Future.delayed(const Duration(seconds: 4));
    // 修正:传入当前迭代的子列表ch,而非整个列表chun
    await c.write(ch, withoutResponse: true);
    await c.read();
    await Future.wait(getValue());
});

说明

  • bytes.sublist(19)会生成原列表从索引19到末尾的新列表,确保后续切片操作从指定位置开始。
  • 移除了原代码中无效的for循环,避免提前返回错误结果。
  • 写入时传入ch而非chun,保证每次发送的是当前拆分后的子列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 01:46:09