1、pubspec文件管理Flutter应用程序的assets(资源,如图片、package等)。 在pubspec.yaml中,通过网址“https://pub.dartlang.org/packages/charts_flutter”确认版本号后,将charts_flutter(0.5.0或更高版本)添加到依赖项列表。
2、在Android Studio的编辑器视图中查看pubspec时,单击右上角的 Packages get,或者在命令行输入“flutter packages get”;这会将依赖包安装到您的项目。
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'dart:math';
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 TimeSeriesSales {
final DateTime time;
final int sales;
TimeSeriesSales(this.time, this.sales);
}
class _MyHomePageState extends State {
int _counter = 4;
final serialdata = [
new TimeSeriesSales(new DateTime(2017, 9, 1), 5),
new TimeSeriesSales(new DateTime(2017, 9, 2), 25),
new TimeSeriesSales(new DateTime(2017, 9, 3), 100),
new TimeSeriesSales(new DateTime(2017, 9, 4), 75),
];
Random random = new Random();
void _incrementCounter() {
setState(() {
_counter++;
serialdata.add(new TimeSeriesSales(new DateTime(2017, 9, _counter), random.nextInt(100)));
});
}
@override
Widget build(BuildContext context) {
List> seriesList = [
new charts.Series(
id: 'Sales',
colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault,
domainFn: (TimeSeriesSales sales, _) => sales.time,
measureFn: (TimeSeriesSales sales, _) => sales.sales,
data: serialdata,
)
];
var chart = new charts.TimeSeriesChart(
seriesList,
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(
children: [
chartWidget,
],
),
),
floatingActionButton: new FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: new Icon(Icons.add),
),
);
}
}