天天看点

Flutter Chart

最近要在一个flutter的应用上实现图表,在官方的库里找到了一个现成的chart library。

pub.dev的地址:

​​https://pub.flutter-io.cn/packages/charts_flutter​​

这个库应该是google官方自己实现的,github的地址是:

​​https://github.com/google/charts​​

他们有一个案例页面:

​​https://google.github.io/charts/flutter/gallery.html​​

使用前,请先在项目根目录下使用pub get进行安装:

flutter pub add charts_flutter      

接着在项目的pubspec.yaml中添加依赖:

dependencies:
  charts_flutter: ^0.12.0      

之后,就可以在dart文件中使用了。

我在lib文件夹下新建了一个pie.dart 的文件:

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

class SimplePieChart extends StatelessWidget {
  final List<charts.Series> seriesList;  final bool animate;
  SimplePieChart(this.seriesList, {this.animate});
  /// Creates a [PieChart] with sample data and no transition.  factory SimplePieChart.withSampleData() {
    return new SimplePieChart(
      _createSampleData(),      // Disable animations for image tests.      animate: false,    );  }

  factory SimplePieChart.withInputData(seriesList) {
    return new SimplePieChart(seriesList, animate: true);  }

  @override  Widget build(BuildContext context) {
    return Container(
      child: new charts.PieChart(seriesList, animate: animate),    );  }

  /// Create one series with sample hard coded data.  static List<charts.Series<LinearSales, int>> _createSampleData() {
    final data = [
      new LinearSales(0, 1),      new LinearSales(1, 99),    ];
    return [
      new charts.Series<LinearSales, int>(
        id: 'Sales',        
        domainFn: (LinearSales sales, _) => sales.year,  
        measureFn: (LinearSales sales, _) => sales.sales,      
        data: data,     
        )
    ];  }
}

/// Sample linear data type.
class LinearSales {
  final int year;  final double sales;
  LinearSales(this.year, this.sales);
  }      

这个文件实现了两个基本类,LinearSales是数据格式,SimplePieChart实现了一个简单的饼图。

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

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Chart',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: '图表'),
    );
  }
}

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

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  double p = 50.0;
  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.

      return Scaffold(
        appBar: AppBar(
          // Here we take the value from the MyHomePage object that was created by
          // the App.build method, and use it to set our appbar title.
          title: Text(widget.title),
        ),
        body: Center(
            child: Column(crossAxisAlignment: CrossAxisAlignment.start,

                // Center is a layout widget. It takes a single child and positions it
                // in the middle of the parent.
                children: [
              Expanded(
                  flex: 3,
                  child: new SimplePieChart.withInputData([
                    new charts.Series<LinearSales, int>(
                      id: 'Sales',
                      domainFn: (LinearSales sales, _) => sales.year,
                      measureFn: (LinearSales sales, _) => sales.sales,
                      data: [
                        new LinearSales(0, 100 - p),
                        new LinearSales(1, p),
                      ],
                    )
                  ])),

            ])),
      );

  }
}