在 dart 中读取文件并拆分字符串在控制台中的结果与 vscode 中的结果不同

Reading a file in dart and split the string has different results in console that in vscode

我是 dart 的新手,我正在尝试从 txt 文件中读取信息并使用数据从 class(在本例中是关于 pokemon)创建对象,但是当我 运行 我在终端中的程序没有打印出正确的信息,当我 运行 在 vscode 中的程序时(whit dart 扩展,“运行”按钮)它在调试控制台中打印正确的信息。有什么问题?

当我 运行 vscode 中的程序时,我在我的打印方法 (printP) 中得到了这个(这就是我想要的)

vscode:

Print method:
1+: Bulbasaur GRASS | POISON

但是当我 运行 终端中的程序时,我得到了这个。

航站楼:

Print method:
 | POISONsaur

这是飞镖代码。

main.dart

import 'dart:io';
import 'pokemon.dart';

void main() {
  var file = new File("/home/ariel/Documents/script/pokemon.txt");
  String str = file.readAsStringSync();
  var pokes = str.split("[");
  pokes = pokes.sublist(1, pokes.length);
  getPokemon(pokes[0]).printP();
}

Pokemon getPokemon(String str) {
  Pokemon p = new Pokemon();
  print("string: " + str);
  var aux = str.split("\n");
  print(aux.length);
  for (var i in aux) {
    print("line: " + i);
  }
  p.number = int.parse(aux[0].split("]")[0]);
  p.name = aux[1].split("=")[1];
  p.type1 = aux[3].split("=")[1];
  p.type2 = aux[4].split("=")[1];
  return p;
}

pokemon.dart

class Pokemon {
  String _name, _type1, _type2;
  int _number;

  Pokemon() {
    this._name = "";
    this._number = 0;
    this._type1 = "";
    this._type2 = "";
  }

  void printP() {
    print("Print method:");
    print("${this._number}+: ${this._name} ${this._type1} | ${this._type2}");
  }

  void set number(int n) {
    this._number = n;
  }

  void set name(String nm) {
    this._name = nm;
  }

  void set type1(String t) {
    this._type1 = t;
  }

  void set type2(String t) {
    this._type2 = t;
  }
}


这里是 txt 文件

pokemon.txt

[1]
Name=Bulbasaur
InternalName=BULBASAUR
Type1=GRASS
Type2=POISON
BaseStats=45,49,49,45,65,65
GenderRate=FemaleOneEighth
GrowthRate=Parabolic
BaseEXP=64
EffortPoints=0,0,0,0,1,0
Rareness=45
Happiness=70
Abilities=OVERGROW
HiddenAbility=CHLOROPHYLL
Moves=1,TACKLE,3,GROWL,7,LEECHSEED,9,VINEWHIP,13,POISONPOWDER,13,SLEEPPOWDER,15,TAKEDOWN,19,RAZORLEAF,21,SWEETSCENT,25,GROWTH,27,DOUBLEEDGE,31,WORRYSEED,33,SYNTHESIS,37,SEEDBOMB
EggMoves=AMNESIA,CHARM,CURSE,ENDURE,GIGADRAIN,GRASSWHISTLE,INGRAIN,LEAFSTORM,MAGICALLEAF,NATUREPOWER,PETALDANCE,POWERWHIP,SKULLBASH,SLUDGE
Compatibility=Monster,Grass
StepsToHatch=5355
Height=0.7
Weight=6.9
Color=Green
Habitat=Grassland
Kind=Seed
Pokedex=Almacena energía en el bulbo de su espalda para alimentarse durante épocas de escasez de recursos o para atacar liberándola de golpe.
BattlerPlayerY=0
BattlerEnemyY=25
BattlerAltitude=0
Evolutions=IVYSAUR,Level,16

您的代码取决于您的 txt 文件的换行符格式。我建议您使用 dart:convert 中的 LineSplitter class 来拆分您的行。

问题是 Windows 换行符同时包含 '\n''\r',但您只删除了 '\n' 部分。 '\r' 是必不可少的,意味着终端应将光标设置回行首。

你可以像打字机一样阅读这篇文章,首先将头部向后移动,然后将纸张移动到下一行。并且可以在这里阅读更多关于主题的信息:https://en.wikipedia.org/wiki/Newline

LineSplitter class 的目的是抽象所有这些逻辑并获得一些适用于所有平台的行为。

因此导入 dart:convert 并更改此行:

var aux = str.split("\n");

进入:

var aux = LineSplitter.split(str).toList();