如何使动态图表波动?

时间:2019-05-08 12:22:44

标签: charts flutter

您好,我尝试制作一个简单的图表,其中x轴为日期,Y轴为数据。当我按下按钮时,当前日期的数据增加。第一个目标是通过以下代码完成的。但是现在我不知道如何使图表更动态,我希望统计每一天的按下按钮的统计信息。我不知道如何为每一天动态添加新的数据列。

import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:intl/intl.dart';
void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class ClicksPerYear {
  final String year;
  final int clicks;
  final charts.Color color;

  ClicksPerYear(this.year, this.clicks, Color color)
      : this.color = new charts.Color(
      r: color.red, g: color.green, b: color.blue, a: color.alpha);
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  var currentTime;
  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    var data = [

      new ClicksPerYear('2015', 3, Colors.red),
      new ClicksPerYear('2016', 7, Colors.orange),
      new ClicksPerYear('2017', 42, Colors.yellow),
      new ClicksPerYear('$currentTime', _counter, Colors.green),
    ];

    var series = [
      new charts.Series(
        domainFn: (ClicksPerYear clickData, _) => clickData.year,
        measureFn: (ClicksPerYear clickData, _) => clickData.clicks,
        colorFn: (ClicksPerYear clickData, _) => clickData.color,
        id: 'Clicks',
        data: data,

      ),
    ];
    var chart = new charts.BarChart(
      series,
      animate: true,
    );

    var chartWidget = new Padding(
      padding: new EdgeInsets.all(32.0),
      child: new SizedBox(
        height: 200.0,
        child: chart,
      ),
    );

    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Text(
              'You have pushed the button this many times:',
            ),
            new Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
            chartWidget,
          ],
        ),
      ),

      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            DateTime now = DateTime.now();
            currentTime = DateFormat('dd/MM/yyyy').format(now);
            _incrementCounter();
          });
        },
        child: Icon(Icons.add,),

      ),

    );
  }
}

1 个答案:

答案 0 :(得分:2)

您共享的代码存在一些小问题。我试图修复它们,并根据您自己的代码准备更新的版本。查看以下提示:

1)对象的状态。

您已经使用了颤动初始示例提供的计数器。此计数器是父窗口小部件的成员变量,并且只有一个计数器可用。因此,您必须使其他栏变为静态!看起来不太好。将其转换为List或Map即可解决,但最好将值保存在对象本身内。

例如,假设您要在另一页中使用2016年数据。您必须从父窗口小部件获取数据并将其传递到新页面。但是,如果您将点击次数保留在对象内部,则只需要传递对象本身即可。

2)Build方法内的局部变量

数据列表是在构建方法的开头定义的。在这种情况下,每当小部件重新构建自身时,它将启动数据列表。看起来不太好!该列表可用,并且应该对其进行任何更改。对其进行完善可能会删除之前的更改。

3)使用地图代替列表

尽管使用List类型作为数据变量没有问题,但我建议改为使用Map类型。如果要使用列表,则每当要对数据元素应用任何更改时,都需要搜索它并找到合适的元素。但是使用Map类型时,您可以只存储密钥并在以后使用。

查看更正后的代码,如果对此有任何疑问,请告诉我:

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

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class ClicksPerYear {
  final String year;
  int clicks;
  final charts.Color color;

  ClicksPerYear(this.year, this.clicks, Color color)
      : this.color = new charts.Color(
            r: color.red, g: color.green, b: color.blue, a: color.alpha);

  incrementClick() {
    clicks++;
  }
}

class _MyHomePageState extends State<MyHomePage> {
  var currentTime = DateFormat('dd/MM/yyyy').format(DateTime.now());
  Map<String, ClicksPerYear> data;

  @override
  void initState() {
    data = {
      '2015': ClicksPerYear('2015', 3, Colors.red),
      '2016': ClicksPerYear('2016', 7, Colors.orange),
      '2017': ClicksPerYear('2017', 42, Colors.yellow),
      '$currentTime': ClicksPerYear('$currentTime', 0, Colors.green),
    };
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var series = [
      new charts.Series(
          domainFn: (ClicksPerYear clickData, _) => clickData.year,
          measureFn: (ClicksPerYear clickData, _) => clickData.clicks,
          colorFn: (ClicksPerYear clickData, _) => clickData.color,
          id: 'Clicks',
          data: data.values.toList()),
    ];
    var chart = new charts.BarChart(
      series,
      animate: true,
    );

    var chartWidget = new Padding(
      padding: new EdgeInsets.all(32.0),
      child: new SizedBox(
        height: 200.0,
        child: chart,
      ),
    );

    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Center(child: chartWidget),
      floatingActionButton: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: FloatingActionButton(
              onPressed: () {
                setState(() {
                  data.putIfAbsent(
                      '2012', () => ClicksPerYear('2012', 42, Colors.teal));
                });
              },
              child: Icon(
                Icons.add,
              ),
              backgroundColor: Colors.red,
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: FloatingActionButton(
              onPressed: () {
                setState(() {
                  DateTime now = DateTime.now();
                  currentTime = DateFormat('dd/MM/yyyy').format(now);
                  data[currentTime].incrementClick();
                });
              },
              child: Icon(
                Icons.add,
              ),
            ),
          ),
        ],
      ),
    );
  }
}