echarts 配置参数跟 web 配置是一样,可以参考web 端官网 来配置,flutter_echarts 采用的是 webview 来加载 html,所以需要安装webview_flutter
1.引入依赖
dart
dependencies:
flutter_echarts: ^0.0.1
webview_flutter: ^0.3.20+3
3.使用
onLoad 回调可以获取到 webview 的 controller,通过 controller 来调用 js 方法
例如调用_controller?.reload() 就可以实现重新渲染图表
dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_echarts/flutter_echarts.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'dart:math' as math;
class TodayEcharts extends StatefulWidget {
const TodayEcharts({super.key});
@override
State<TodayEcharts> createState() => _TodayEchartsState();
}
class _TodayEchartsState extends State<TodayEcharts> {
late WebViewController _controller;
List<Map<String, Object>> _data1 = [
{'name': 'Please wait', 'value': 0}
];
getData1() async {
await Future.delayed(const Duration(seconds: 4));
List<Map<String, Object>> dataObj = [];
for (var i = 0; i < 7; i++) {
int randomInt = math.Random().nextInt(100);
dataObj.add(
{
'name': 'Jan$i',
'value': randomInt,
},
);
}
if (mounted) {
setState(() {
_data1 = dataObj;
});
}
}
@override
void initState() {
super.initState();
getData1();
}
@override
void dispose() {
super.dispose();
}
@override
Widget build(BuildContext context) {
List nameList = _data1.map((item) => item['name']).toList();
List valueList = _data1.map((item) => item['value']).toList();
return SizedBox(
width: MediaQuery.of(context).size.width,
height: 450,
child: Echarts(
option: jsonEncode({
"legend": {
"x": 'center',
"y": 'bottom',
"show": true,
"textStyle": {
//图例的公用文本样式。
"fontSize": 14,
"color": "#333",
},
"itemGap": 20, //图例每项之间的间隔。横向布局时为水平间隔,纵向布局时为纵向间隔。
"data": ['项目金额(万元)', '项目数量'], //图例的数据数组。
"inactiveColor": '#ccc',
},
"xAxis": {
//X轴数据
"type": "category",
"data": nameList,
},
"yAxis": [
{
//Y轴数据
"type": "value",
"splitNumber": "5",
"name": "万元",
"axisLabel": {
"color": '#027eff' // 修饰刻度标签的颜色
},
"nameTextStyle": {
"color": "#027eff",
}
},
{
"type": 'value',
"min": '0', //最小坐标
"max": '12', //最大坐标
"splitLine": {
"show": false //是否显示分隔线。
},
"name": "个",
"axisLabel": {
"color": '#FF9800' // 修饰刻度标签的颜色
},
"nameTextStyle": {
"color": "#FF9800",
}
}
],
"series": [
{
//对应点得值
"name": "项目金额(万元)",
"data": valueList,
"barWidth": '50%',
"type": "bar",
"itemStyle": {
"normal": {
"barBorderRadius": 0,
"color": {
"type": 'linear',
"x": 0,
"y": 0,
"x2": 0,
"y2": 1,
"colorStops": [
{
"offset": 0,
"color": '#00feff',
},
{
"offset": 1,
"color": '#027eff',
},
{
"offset": 1,
"color": '#0286ff',
},
],
},
},
}
},
],
}),
extraScript: '''
chart.on('click', (params) => {
if(params.componentType === 'series') {
Messager.postMessage(JSON.stringify({
type: 'select',
payload: params.dataIndex,
}));
}
});
''',
onLoad: (controller){
_controller = controller;
},
reloadAfterInit: true,
onMessage: (message) {
print("点击图形信息$message");
},
),
);
}
}