Flutter - JSON and Time Series Charts

后端 未结 2 1982
攒了一身酷
攒了一身酷 2021-01-14 19:48

I am trying to display some data in a time-series chart, I found an example \"https://google.github.io/charts/flutter/example/time_series_charts/simple.html\" but the data i

相关标签:
2条回答
  • 2021-01-14 20:21

    The first thing to do is to refactor TimeSeriesSales so that it makes sense in your application, for example:

    class TimeSeriesPrice {
      final DateTime time;
      final double price;
      TimeSeriesSales(this.time, this.price);
    }
    

    Next, you need to build data.

    List<TimeSeriesPrice> data = [];
    // populate data with a list of dates and prices from the json
    for (Map m in dataJSON) {
      data.add(TimeSeriesPrice(m['date'], m['price']);
    }
    var series = ... 
    

    You don't give an example of the json format, so this is a guess. (You are likely to have to parse the json string date into a Dart DateTime.)

    0 讨论(0)
  • 2021-01-14 20:21

    @Richard Heap, thanks for your prompt reply. According to your advice. I modified the source code as the following.

    1. I encountered the NULL pointer of dataJSON. To overcome this problem, applied some exceptional handling.
    2. When draw the chart, I encountered that the data(dataJSON) was delayed, I added a dummy list to handle the exception.

    Please feel free to comment.

    import 'dart:async';
    import 'dart:convert';
    import 'package:http/http.dart' as http;
    
    import 'package:charts_flutter/flutter.dart' as charts;
    import 'package:flutter/material.dart';
    
    // JSON format
    // {"Response":"Success","Type":100,"Aggregated":false,"Data":
    // [{"time":1279324800,"close":0.04951,"high":0.04951,"low":0.04951,"open":0.04951,"volumefrom":20,"volumeto":0.9902},
    
    /// Time-series data type.
    class TimeSeriesPrice {
      final DateTime time;
      final double price;
      TimeSeriesPrice(this.time, this.price);
    }
    
    class ItemDetailsPage extends StatefulWidget {
      @override
      _ItemDetailsPageState createState() => new _ItemDetailsPageState();
    }
    
    class _ItemDetailsPageState extends State<ItemDetailsPage> {
      String url =
          "https://min-api.cryptocompare.com/data/histoday?fsym=BTC&tsym=USD&limit=1&aggregate=1&allData=true";
    
      List dataJSON;
    
      Future<String> getCoinsTimeSeries() async {
        var response = await http
            .get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
    
        if (this.mounted) {
          this.setState(() {
            var extractdata = json.decode(response.body);
            dataJSON = extractdata["Data"];
          });
        }
      }
    
      @override
      void initState() {
        this.getCoinsTimeSeries();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: new AppBar(title: new Text("Details")),
          body: chartWidget(),
        );
      }
    
      Widget chartWidget() {
        List<TimeSeriesPrice> tsdata = [];
        if (dataJSON != null) {
          for (Map m in dataJSON) {
            try {
              tsdata.add(new TimeSeriesPrice(
                  new DateTime.fromMillisecondsSinceEpoch(m['time'] * 1000, isUtc: true), m['close']+.0));
            } catch (e) {
              print(e.toString());
            }
          }
        } else {
          // Dummy list to prevent dataJSON = NULL
          tsdata.add(new TimeSeriesPrice(new DateTime.now(), 0.0));
        }
    
        var series = [
          new charts.Series<TimeSeriesPrice, DateTime>(
            id: 'Price',
            colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault,
            domainFn: (TimeSeriesPrice coinsPrice, _) => coinsPrice.time,
            measureFn: (TimeSeriesPrice coinsPrice, _) => coinsPrice.price,
            data: tsdata,
          ),
        ];
    
        var chart = new charts.TimeSeriesChart(
          series,
          animate: true,
        );
    
        return new Container(
          child: new Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              new Padding(
                padding: new EdgeInsets.all(32.0),
                child: new SizedBox(
                  height: 200.0,
                  child: chart,
                ),
              ),
            ],
          ),
        );
      }
    }
    
    0 讨论(0)
提交回复
热议问题