使用dart.io读取二叉树结构TXT文件时出现错误的问询
Hey there! Let's figure out why you're hitting that weird "Expected a declaration, but got '75'" error and fix it up.
First, let's break down the likely causes
That error message makes it seem like the Dart parser is treating your text file's content as actual code, which doesn't make sense if you're just reading it into a string. Here are the most common issues:
Incorrect code structure (top-level expression statements)
If you were running the file read operation as a standalone expression at the top level (not assigned to a variable or inside a function), Dart would throw a syntax error because top-level code can only include declarations (variables, functions, classes). Even though your code shows an assignment tocontents, double-check that your full code doesn't have stray expressions outside functions.Wrong file path leading to unexpected behavior
If your path./assets/triangle.txtis incorrect (e.g., the folder doesn't exist, typo in the filename), Dart might throw an error—but sometimes IDEs can misreport where the error is. Path issues are a super common culprit for file read failures, even if the error message points to your file's content.Missing error handling masking the real problem
If the file read fails (e.g., permissions, file not found), the uncaught exception might cause your IDE to show a misleading error message pointing to the file's content instead of the actual read failure.
Fixes to try out
Let's go step by step to resolve this:
1. Wrap file operations in main() with error handling
While top-level variable initializations can call functions like readAsStringSync, putting the read logic inside main() with a try-catch block will help you see the real error if something goes wrong:
import 'dart:io'; void main() { try { // New keyword is optional in modern Dart String contents = File('./assets/triangle.txt').readAsStringSync(); print('Successfully read file! First line: ${contents.split('\n').first}'); // Add your binary tree processing logic here } catch (e) { print('Error reading file: $e'); // This will show the real issue (path, permissions, etc.) } }
2. Verify your file path is correct
- Make sure the
assetsfolder is in your project's root directory (the same folder where yourpubspec.yamlor main Dart file lives). - Test with an absolute path to rule out relative path issues:
// Example for macOS/Linux String absolutePath = '/Users/your-username/your-project-folder/assets/triangle.txt'; // Example for Windows String absolutePath = 'C:\\your-project-folder\\assets\\triangle.txt'; String contents = File(absolutePath).readAsStringSync(); - If the absolute path works, check your IDE's run configuration—sometimes the working directory isn't set to your project root.
3. Check your text file's encoding
Ensure triangle.txt uses UTF-8 encoding without a Byte Order Mark (BOM). Some text editors add a BOM which can cause unexpected characters at the start of your string, leading to parsing issues later. You can fix this in VS Code by opening the file, clicking the encoding label in the bottom-right corner, and selecting "UTF-8".
4. Correct way to read line-by-line
If you want to read the file line-by-line (great for large files), use this async approach:
import 'dart:io'; import 'dart:convert'; void main() async { try { Stream<String> lines = File('./assets/triangle.txt') .openRead() .transform(utf8.decoder) .transform(const LineSplitter()); await for (String line in lines) { print('Processing line: $line'); // Split line into digits, e.g., List<String> digits = line.split(' '); } } catch (e) { print('Error reading lines: $e'); } }
Since you mentioned that hardcoding the file content as a string variable works, your binary tree processing logic is probably fine—this issue is definitely tied to how you're reading the external file.
内容的提问来源于stack exchange,提问作者Codin Hill

