如何自动包装chart_flutter图例?
我尝试过
behaviors: [charts.SeriesLegend(desiredMaxColumns: 2)],
但是,它已经固定为两列。 行数和图例长度是可变的。
我该怎么办?
答案 0 :(得分:3)
这不是开箱即用的解决方案,但是您可以创建自己的自定义图例生成器并布局图例,但可以通过扩展charts.LegendContentBuilder
类来实现。
class CustomLegendBuilder extends charts.LegendContentBuilder{
@override
Widget build(BuildContext context, LegendState legendState, Legend legend, {bool showMeasures}) {
/*
Implement your custom layout logic here. You should take into account how long
your legend names are and how many legends you have. For starters you
could put each legend on its own line.
*/
return Container(
color: Colors.red,
height: 25.0,
child: Text('MY CUSTOM LEGEND'),
);
}
}
现在,当您构建图表时,请添加以下行为:
...
behaviors: [
charts.SeriesLegend.customLayout(
CustomLegendBuilder(),
// Other legend properties here
),
],
...
答案 1 :(得分:0)
此问题的示例代码。
import 'package:flutter/material.dart';
import 'dart:math';
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(
home: Scaffold(
appBar: AppBar(),
body: SimpleLineChart.withRandomData(),
));
}
}
class SimpleLineChart extends StatelessWidget {
final List<charts.Series> seriesList;
SimpleLineChart(this.seriesList);
factory SimpleLineChart.withRandomData() {
return SimpleLineChart(
_createRandomData(),
);
}
/// Create random data.
static List<charts.Series<LinearSales, num>> _createRandomData() {
final random = Random();
List<charts.Series<LinearSales, int>> s = [];
for (var i = 0; i < random.nextInt(6); ++i) {
final data = [
LinearSales(0, random.nextInt(100)),
LinearSales(1, random.nextInt(100)),
LinearSales(2, random.nextInt(100)),
LinearSales(3, random.nextInt(100)),
];
String title1 = random.nextInt(1000).toString();
String title2 = random.nextInt(10000).toString();
s.add(
charts.Series<LinearSales, int>(
id: 'legend_${title1}_${title2}',
domainFn: (LinearSales sales, _) => sales.year,
measureFn: (LinearSales sales, _) => sales.sales,
data: data,
),
);
}
return s;
}
@override
Widget build(BuildContext context) {
return charts.LineChart(
seriesList,
behaviors: [charts.SeriesLegend()],
);
}
}
/// Sample linear data type.
class LinearSales {
final int year;
final int sales;
LinearSales(this.year, this.sales);
}
答案 2 :(得分:0)
答案 3 :(得分:0)
您可以简单地检查屏幕的宽度并动态设置所需的MaxColumns:
@override
Widget build(BuildContext context) {
// workaround for not-available auto-wrapping of legend
double width = MediaQuery.of(context).size.width;
int maxColumns;
// change width thresholds according to your needs
if (width < 600 && width >= 500) {
maxColumns = 3;
} else if (width < 500 && width >= 400) {
maxColumns = 2;
} else if (width < 400) {
maxColumns = 1;
}
return charts.LineChart(
seriesList,
behaviors: [new charts.SeriesLegend(desiredMaxColumns: maxColumns)]
);
}