Home > Software engineering >  How to show JSON Data in Line Chart in Flutter?
How to show JSON Data in Line Chart in Flutter?

Time:07-02

I want to draw a line chart catching the data from a JSON file. The JSON is inside the assets folder. But I do not know How to Develop a Line Chart using my JSON Data. Can please somebody help and guide me. Thank you very much.

Here is the JSON

{
  "measure": [
    {
      "count": 8,
      "range_array": [20.6, 27.9, 50.6],
      "force_array": [116.8, 187.4, 226.6]
    }
  ]
}

Here is the Model

class DataModel {
  DataModel({this.measure});

  List<DataTitle>? measure;

  factory DataModel.fromJson(Map<String, dynamic> json) {
    return DataModel(
      measure: List<DataTitle>.from(
          json['measure'].map((c) => DataTitle.fromJson(c)).toList()),
    );
  }
}

class DataTitle {
  DataTitle(
      {required this.number,
      required this.firstarray,
      required this.secondarray});

  int? number;
  List<double>? firstarray;
  List<double>? secondarray;

  DataTitle.fromJson(Map<String, dynamic> json) {
    number = json['count'];
    firstarray = json['range_array'] == null
        ? []
        : List<double>.from(json['range_array'].map((x) => x.toDouble()));
    secondarray = json['force_array'] == null
        ? []
        : List<double>.from(json['force_array'].map((x) => x.toDouble()));
  }
  @override
  String toString() {
    return 'DATA TITLE{Count: $number, RangeArray: $firstarray, ForceArray: $secondarray}';
  }
}

Here is the where i want to display the Chart

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:convert';
import 'package:read_local_json/measure_data_model.dart';
import 'dart:async' show Future;

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'JSON',
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  HomeState createState() => HomeState();
}

class HomeState extends State<Home> {
  Future loadData() async {
    final jsonString = await rootBundle.loadString('assets/measurelist.json');
    final decodedJson = json.decode(jsonString);
    List<DataTitle> dataTileList = (decodedJson['measure'] as List)
        .map((jsonElement) => DataTitle.fromJson(jsonElement))
        .toList();
    print(dataTileList.first);
    print(dataTileList.last);
  }

  @override
  void initState() {
    super.initState();
    loadData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('JSON Chart'),
      ),
      body: const Center(
        child: Text('JSON Chart'),
      ),
    );
  }
}

CodePudding user response:

The JSON data can be converted to a list with the help of the json.decode function.

import 'dart:convert';

final List<Measure> measures = (json.decode(jsonstring)['measure'] as List).map((i) => Measure.fromJson(i)).toList();
class Measure {
  final int count;
  final List<double> range_array;
  final List<double> force_array;
  Measure({this.count, this.range_array, this.force_array});
  factory Measure.fromJson(Map<String, dynamic> json) {
    return Measure(
    count: json['count'],
    range_array: json['range_array'],
    force_array: json['force_array'],
    );
  }
}

After that, use a charts package to draw the line chart.

LineChart(
  data: LineChartData(
  points: measures[0].count.toList().asMap().entries.map((key) => DataPoint(key.key.toDouble(), measures[0].force_array[key.key])).toList(),
  ),
);
  • Related