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

Flutter中使用rootBundle loadString加载外部导出CSV文件时遭遇FormatException问题求助

Troubleshooting Flutter rootBundle.loadString() CSV Loading Issue

Hey there! Let's break down why your CSV file is acting up when loading with rootBundle.loadString()—and why opening it in Excel fixes things temporarily. From what you've described, there are a couple of key suspects here, and we can tackle them step by step.

1. The Hidden Culprit: UTF-8 BOM (Byte Order Mark)

First, let's circle back to the encoding angle you mentioned. Even if you thought encoding wasn't the issue, Excel might be fixing a UTF-8 with BOM problem without you noticing. Some external tools export CSV files with a hidden BOM (a 3-byte marker at the start of the file). Flutter's rootBundle.loadString() defaults to plain UTF-8, which doesn't handle BOMs well—this can throw off parsing before you even get to the CSV converter.

When you open the file in Excel and save it, Excel automatically strips out the BOM, which is why loading works afterward. To confirm this, open your original CSV file in a text editor like Notepad++ and check the encoding (look for "UTF-8-BOM" in the encoding menu).

2. Your Suspected Issue: Trailing Blank Lines with Newlines

Your hunch about trailing blank lines is totally valid. Extra newlines at the end of the file can cause CsvToListConverter to create empty rows, which might lead to index errors (like trying to access items[4] on an empty row). Excel likely trims these trailing empty lines when saving, which resolves the problem.

Fixes to Implement

Let's adjust your code to handle both potential issues:

Step 1: Strip BOM and Clean Trailing Content

Modify the string right after loading it to remove any BOM and trim trailing empty lines:

initClient() async {
  // Load the file string
  var myCsvFile = await rootBundle.loadString('assets/csv2.txt');
  
  // Remove UTF-8 BOM if present (the first character is \uFEFF)
  if (myCsvFile.startsWith('\uFEFF')) {
    myCsvFile = myCsvFile.substring(1);
  }
  
  // Trim trailing newlines and empty lines to avoid empty rows
  myCsvFile = myCsvFile.trimRight();
  
  // No need for the encode/decode loop—loadString already returns a UTF-8 string
  var rowAsListValues = const CsvToListConverter(fieldDelimiter: '\t', eol: '\n')
      .convert(myCsvFile);
  
  var parsedList = [];
  for (var items in rowAsListValues) {
    // Add a safety check to avoid index errors if a row is unexpectedly short
    if (items.length >= 5 && items[4] < 0) {
      parsedList.add(items);
    }
  }
  return parsedList;
}

Step 2: Verify File Format

  • Open your original CSV file in a text editor and ensure line endings are consistent (stick to \n or \r\n—Excel standardizes this on save).
  • Double-check that tab delimiters (\t) are used consistently (no accidental spaces instead of tabs, which Excel will auto-correct).

Why Excel Fixes It

When you open and save the file in Excel, it does a few behind-the-scenes fixes that resolve the issue:

  • Removes UTF-8 BOM markers
  • Standardizes line endings to match your system
  • Trims trailing empty rows
  • Ensures consistent delimiters

By replicating these fixes in your code, you won't need to rely on Excel to prep the file anymore.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 18:12:47