在此示例中,如何从Internet提取数据?

时间:2018-07-24 15:09:19

标签: dart flutter

这是Flutter应用程序的简单BarChart的一个官方示例-https://google.github.io/charts/flutter/example/bar_charts/simple

我喜欢从互联网上获取此图表的数据。这是数据-http://skazkimal.ru/hr-metrics/headcount.json

我的代码不起作用,因为方法_createSampleData是异步的:

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:hr_metrics/FetchChartData.dart';
import 'package:http/http.dart' as http;

class SalaryView extends StatelessWidget{

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('FFFFFFFFF'),

      ),
      body: Padding(
        padding: const EdgeInsets.all(10.0),
        child: new SalaryChart.withSampleData(),
      ),
    );
  }

}

class SalaryChart extends StatelessWidget{
  final List<charts.Series> seriesList;
  final bool animate;

  SalaryChart(this.seriesList, {this.animate});

  /// Creates a [BarChart] with sample data and no transition.
  factory SalaryChart.withSampleData() {
    return new SalaryChart(
      _createSampleData(),
      // Disable animations for image tests.
      animate: true,
    );
  }

  @override
  Widget build(BuildContext context) {
    // This is just a simple bar chart with optional property
    // [defaultInteractions] set to true to include the default
    // interactions/behaviors when building the chart.
    // This includes bar highlighting.
    //
    // Note: defaultInteractions defaults to true.
    //
    // [defaultInteractions] can be set to false to avoid the default
    // interactions.
    return new charts.BarChart(
      seriesList,
      animate: animate,
      defaultInteractions: true,
      barRendererDecorator: new charts.BarLabelDecorator<String>(),
      vertical: false,
    );
  }

  /// Create one series with sample hard coded data.

  static Future<List<charts.Series<ChartData, String>>> _createSampleData() async {
    final data = await fetchData(http.Client());

    return [
      new charts.Series<ChartData, String>(
          id: 'Numbers',
          domainFn: (ChartData series, _) => series.period,
          measureFn: (ChartData series, _) => series.count,
          data: data,
          labelAccessorFn: (ChartData series, _) => '${series.count.toString()}'
      )
    ];
  }

}

/// Sample ordinal data type.

class OrdinalSalary {
  final String year;
  final int salary;

  OrdinalSalary(this.year, this.salary);
}

1 个答案:

答案 0 :(得分:0)

您不能在这样的构造函数中使用异步方法。相反,您应该像这样创建一个异步方法:

static Future<SalaryChart> withSampleData() => _createSampleData().then((data) => SalaryChart(data, animate: true));

您将在其他地方使用哪个

SalaryChart myChart = await SalaryChart.withSampleData();