在flutter页面中显示一个显示随机数据的曲线图
时间: 2024-02-24 20:58:35 浏览: 111
要在Flutter页面中显示一个随机数据的曲线图,可以使用Flutter中的charts_flutter库。以下是实现的步骤:
1. 在pubspec.yaml文件中添加charts_flutter库的依赖:
```
dependencies:
charts_flutter: ^0.9.0
```
2. 导入charts_flutter库:
```
import 'package:charts_flutter/flutter.dart' as charts;
```
3. 创建一个随机数据的List:
```
List<charts.Series> _createRandomData() {
final data = [
new MyData(0, _getRandomInt()),
new MyData(1, _getRandomInt()),
new MyData(2, _getRandomInt()),
new MyData(3, _getRandomInt()),
new MyData(4, _getRandomInt()),
new MyData(5, _getRandomInt()),
];
return [
new charts.Series<MyData, int>(
id: 'Data',
domainFn: (MyData data, _) => data.index,
measureFn: (MyData data, _) => data.value,
data: data,
)
];
}
class MyData {
final int index;
final int value;
MyData(this.index, this.value);
}
int _getRandomInt() {
return new Random().nextInt(100);
}
```
4. 创建一个LineChart:
```
charts.LineChart(
_createRandomData(),
animate: true,
animationDuration: Duration(milliseconds: 500),
)
```
完整的示例代码如下:
```
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: charts.LineChart(
_createRandomData(),
animate: true,
animationDuration: Duration(milliseconds: 500),
),
),
);
}
List<charts.Series> _createRandomData() {
final data = [
new MyData(0, _getRandomInt()),
new MyData(1, _getRandomInt()),
new MyData(2, _getRandomInt()),
new MyData(3, _getRandomInt()),
new MyData(4, _getRandomInt()),
new MyData(5, _getRandomInt()),
];
return [
new charts.Series<MyData, int>(
id: 'Data',
domainFn: (MyData data, _) => data.index,
measureFn: (MyData data, _) => data.value,
data: data,
)
];
}
int _getRandomInt() {
return new Random().nextInt(100);
}
}
class MyData {
final int index;
final int value;
MyData(this.index, this.value);
}
```
注意:由于图表是随机生成的,每次运行应用程序时都会有不同的结果。
阅读全文