首页 > 解决方案 > 使用 Flutter 图表添加自定义 primaryMeasureAxis

问题描述

我正在尝试使用 Y 轴(垂直轴)进行 TimeSeriesChart 具有自定义标签。

我可以验证字符串 (' final List<dynamic> string = data.data['options'];') 是否包含我期望的值。我什至可以像字符串 [0] 一样引用它们,但是当我这样做strings[value.toInt()]时会抛出RangeError.

看这段代码。在我初始化“最终标签”的地方,我有两行代码定义了一个BasicNumericTickFormatterSpec.

第一行是我想要做的。我想使用value来查找strings[].

我可以做到((num value) => 'MyValue: ${string[0]}'),效果很好。我可以做((num value) => 'MyValue: ${string}')的只是输出每个“步骤”上的所有值。

所以,基本上我可以验证它string实际上保存了我期望的值,并且我可以访问这些值,但是如果我尝试查找一个值,((num value) => 'MyValue: ${string[value.toInt()]}')那么它会因这个 RangeError 而中断。

Widget _buildChart(BuildContext context, DocumentSnapshot data) {
    final List<dynamic> string = data.data['options'];

    final labels =
    charts.BasicNumericTickFormatterSpec((num value) =>  'MyValue: ${string[value.toInt()]}');
    // charts.BasicNumericTickFormatterSpec((num value) =>  'MyValue: ${string[0]}')

    var chart = charts.TimeSeriesChart(seriesList,
        // Sets up a currency formatter for the measure axis.
        primaryMeasureAxis: new charts.NumericAxisSpec(tickFormatterSpec: labels),
        animate: animate,
        // Optionally pass in a [DateTimeFactory] used by the chart. The factory
        // should create the same type of [DateTime] as the data provided. If none
        // specified, the default creates local date time.
        dateTimeFactory: const charts.LocalDateTimeFactory());

    return new Padding(
        padding: new EdgeInsets.all(10.0),
        child: new SizedBox(
          height: 200.0,
          child: chart,
        ));
  }

我希望我输入的每个“值”((num value) => '$strings[value.toInt()])都会从字符串 [] 返回一个字符串。

相反,我得到:

颤振:在 performLayout() 期间引发了以下 RangeError:颤振:RangeError(索引):无效值:不在 0..1 范围内,包括:2

标签: flutter

解决方案


尝试扩展您的刻度格式化程序闭包,以便获得更多诊断信息:

final labels = charts.BasicNumericTickFormatterSpec((num value) {
  var index = value.floor();
  print('--- tick for $value in $string with $index ---');
  return (index < string.length)
      ? 'MyValue: ${string[index]}'
      : 'overflow ${string.length} $index';
});

推荐阅读