简体   繁体   中英

Convert string to double in csv loader (flutter)

I have a csv dataset which contains numerical data. eg:

76.21203492,30.86714946,0

76.23332579,30.86005251,1

76.14016701,30.85789648,2

I am reading this data using the following function:

loadAsset() async {
    final myData = await rootBundle
        .loadString("assets/data.csv");
    List<List<dynamic>> csvTable = CsvToListConverter().convert(myData);

    data = csvTable;
  }

Now, I want to read the values.

  Future<void> _onMapCreated(GoogleMapController controller) async {
    await loadAsset();
    setState(() {
      _markers.clear();
      int k = 0;
      for (final loc in data) {
        final marker = Marker(
          markerId: MarkerId(loc[2]),
          position: LatLng(double.parse(loc[0]), double.parse(loc[1])),
          infoWindow: InfoWindow(
            title: loc[2],
            snippet: loc[2],
          ),
        );
        _markers[k.toString()] = marker;
        k++;
      }
    });

But I am unable to do so. It gives an error in line LatLng(double.parse(loc[0]), double.parse(loc[1])) quoting:

type 'double' is not a subtype of type 'String'

I also tried using the following function:

  double convertion(String number) {
    double value = 0;
    int i = 0;
    List<int> list = number.codeUnits.toList();
    String zero = '0';
    List<int> zeros = zero.codeUnits.toList();
    while (number[i] != '.') {
      value *= 10;
      value += list[i].toDouble() - zeros[0].toDouble();
      i++;
    }
    i++;
    double decimal = 0;
    int k = 0;
    while (i < list.length) {
      k++;
      decimal *= 10;
      decimal += list[i].toDouble() - zeros[0].toDouble();
      i++;
    }
    decimal *= (pow(10, (k * (-1))));
    value += decimal;
    return value;
  }

But I get the same error.

CsvToListConverter automatically parses all ints and doubles into the correct type, so double.parse(loc[0]) gives you an error because loc[0] is already a double, and you obviously can't parse a double from a double.

To fix this, change the line as follows:

From:

LatLng(double.parse(loc[0]), double.parse(loc[1]))

To:

LatLng(loc[0], loc[1])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM