0
votes

I am trying to display line chart from local JSON file in flutter. This is my JSON file,

[
  {
    "time": "20",
    "distance": "10"

  },
  {
    "time": "25",
    "distance": "30"

  }
]

This is the code where I am getting Json data from file in asset and decoding and map it in dart but it shows some error regarding Mapping.

import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'dart:convert';

class HomePage extends StatefulWidget {
  final Widget child;

  HomePage({Key key, this.child}) : super(key: key);

  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<charts.Series<Calculation, int>> seriesBarData;

  _generateData() async {
    final load =
        await DefaultAssetBundle.of(context).loadString("asset/data.json");

    var decoded = json.decode(load);
    List<Calculation> chartdata = [];
    for (var item in decoded) {
      chartdata.add(Calculation.fromJson(item));
    }

    seriesBarData.add(charts.Series(
      data: chartdata,
      domainFn: (Calculation chartdata, _) => chartdata.time,
      measureFn: (Calculation chartdata, _) => chartdata.distance,
      id: 'Performance',
    ));
    setState(() {});
  }

  @override
  void initState() {
    super.initState();
    seriesBarData = List<charts.Series<Calculation, int>>();
    _generateData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.cyan,
        title: Center(child: Text('flutter charts')),
      ),
      body: Column(
        children: [
          Text(
            'Distance to Lane',
            style: TextStyle(fontSize: 24.0, fontWeight: FontWeight.bold),
          ),
          SizedBox(
            height: 10.0,
          ),
          if (seriesBarData.length > 0)
            Expanded(
              child: charts.LineChart(
                seriesBarData,
                animate: true,
                animationDuration: Duration(seconds: 5),
                domainAxis: new charts.OrdinalAxisSpec(
                    //viewport: new charts.OrdinalViewport('AePS', 9),
                    ),

              ),
            )
          else
            Container(),
        ],
      ),
    );
  }
}

class Calculation {
  int time;
  int distance;

  Calculation(this.time, this.distance);

  Calculation.fromJson(Map<int, dynamic> json) {
    time = json['time'];
    distance = json['distance'];
  }
}

; I have found that this error is regarding with Mapping of JSON as I am new to flutter and JSON so I do not know how to map it and use it in code.

1

1 Answers

1
votes

change your fromJson constructor to

 Calculation.fromJson(Map<String, dynamic> json) {
    time = json['time'];
    distance = json['distance'];
  }

Also time and distance property is String