Search code examples
arrayslistdartarraylistini

How to read and write an .ini file in dart


I need to read and write a ini list and make a new list out of it. Problem is that the structure of list is very complex and I am not getting how I can split it to a new list. List structure I have :

PaPo.1.GeoC=47.67207493,10.4114204
PaPo.2.GeoC=47.67208264,10.41141356
PaPo.3.GeoC=47.67209035,10.41140671
PaPo.4.GeoC=47.67209805,10.41139984
PaPo.5.GeoC=47.67210575,10.41139297

List Structure I want:

location:{
lat : 47.67207493
long : 10.4114204
lat : 47.67208264
long : 10.4114204
lat : 47.67207493
long : 10.4114204
lat : 47.67209805
long : 10.41139297
};

Solution

  • I assume you want a JSON output of the form:

    {"location": [
      {"lat": ...
       "long": ...},
      {"lat": ...
       "long": ...},
       ...
    ]}
    

    which your list structure output suggests, but doesn't say directly.

    You can use a package to read ini files, but since the format you are inputting is so consistent and clear, I'd probably just parse it manually:

    final _lineRE = RegExp(r"^PaPo\.(\d+)\.GeoC=([\d.]+),([\d.]+)$", 
        multiline: true);
    Map<String, List<Map<String, double>>> readIniFile(String filename) {
      var source = File(filename).readAsStringSync();
      return {"location": [for (var match in _lineRE.allMatches(source))   
          {"lat": double.parse(match[2]), "long": double.parse(match[3])}
      ]};
    }
    

    (If the inputs are not necessarily in numerical order, you might need to also take int.parse(match[1]) into account.)