一尘不染

如何在flutter图表中显示JSON数据

flutter

我还不太熟悉,我一直试图在条形图中显示来自http请求的一些数据。我找不到任何示例。我希望你们中的一些可以帮助:)

我虽然使用了在线画廊中的这张图表。我刚刚为我的应用更改了类的名称:

import 'package:flutter/material.dart';

import 'package:charts_flutter/flutter.dart' as charts;



class SimpleSeriesLegend extends StatelessWidget {

  final List<charts.Series> seriesList;

  final bool animate;



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



  factory SimpleSeriesLegend.withSampleData() {

    return new SimpleSeriesLegend(

      _createSampleData(),

      // Disable animations for image tests.

      animate: false,

    );

  }



  @override

  Widget build(BuildContext context) {

    return new charts.BarChart(

      seriesList,

      animate: animate,

      barGroupingType: charts.BarGroupingType.grouped,

      // Add the series legend behavior to the chart to turn on series legends.

      // By default the legend will display above the chart.

      behaviors: [new charts.SeriesLegend()],

    );

  }



  /// Create series list with multiple series

  static List<charts.Series<LiveWerkzeuge, String>> _createSampleData() {

    final tool1Data = [

      new LiveWerkzeuge ('WSP1', 5),

      new LiveWerkzeuge ('WSP2', 25),

      new LiveWerkzeuge ('WSP3', 80),

      new LiveWerkzeuge ('WSP4', 75),

      new LiveWerkzeuge ('WSP5', 65),

      new LiveWerkzeuge ('WSP6', 55),

      new LiveWerkzeuge ('WSP7', 70),

      new LiveWerkzeuge ('WSP8', 90),

    ];



    return [

      new charts.Series<LiveWerkzeuge, String>(

        id: 'WZG1',

        domainFn: (LiveWerkzeuge wear, _) => wear.wsp,

        measureFn: (LiveWerkzeuge wear, _) => wear.belastung,

        data: tool1Data,

      ),

    ];

  }



}

/// Sample ordinal data type.

class LiveWerkzeuge {

  final String wsp;

  final int belastung;



  LiveWerkzeuge(this.wsp, this.belastung);

}

抱歉,这是正确显示我的代码的唯一方法。

我发现这是一个简单的代码,用于在ListView中访问和显示数据并自动更新。我只是想学习如何做到这一点,所以对我有用:

import 'dart:async';

import 'dart:convert';



import 'package:flutter/material.dart';



import 'package:http/http.dart' as http;



void main() => runApp(new MyApp());



class MyApp extends StatelessWidget {

  // This widget is the root of your application.

  @override

  Widget build(BuildContext context) {

    return new MaterialApp(

      home: new MyHomePage(),

    );

  }

}



class MyHomePage extends StatefulWidget {

  @override

  _MyHomePageState createState() => new _MyHomePageState();

}



class _MyHomePageState extends State<MyHomePage> {

  String url = 'http://localhost/werkzeug/public/api/data_tool1';

  List data;

  Timer timer;



  Future<String> makeRequest() async {

    var response = await http

        .get(Uri.encodeFull(url), headers: {"Accept": "application/json"});



    setState(() {

      var extractdata = JSON.decode(response.body);

      data = extractdata;

    });

  }



  @override

  void initState() {

    super.initState();

    timer = new Timer.periodic(new Duration(seconds: 2), (Timer timer) async {

      this.makeRequest();

    });

  }



  @override

  void dispose() {

    super.dispose();

    timer.cancel();

  }



  @override

  Widget build(BuildContext context) {

    return new Scaffold(

        appBar: new AppBar(

          title: new Text('Tool Data'),

        ),

        body: new ListView.builder(

            itemCount: data == null ? 0 : data.length,

            itemBuilder: (BuildContext context, int i) {

              return new ListTile(

                title: new Text('Tool 1 Temperature is : ''${data[i]["temp1"]}' ' and tool 2 is: ''${data[i]["temp2"]}'),

              );

            }

        )

    );

  }

}

现在,我想将两者结合起来。

数据如下所示:

[{“ timestamp”:“ 2018-06-29 14:39:18”,“ rpm”:0,“ rpm_filter”:0,“ accel”:0,“
temp1”:104,“ temp2”:746,“ temp3“:134,” temp4“:77,” temp5“:0,” temp6“:0,”
temp7“:0,” temp8“:0,” DMS1“:0,” DMS2“:0,” DMS3“ :0,“ DMS4”:0,“ batt”:0,“
shock”:0,“ shock_accel”:0,“ shock_degxy”:0,“ shock_degxz”:0,“错误”:0,“
connection_id”:0 ,“ Wear1”:0,“ Wear2”:0,“ Wear3”:0:“ Wear4”:0,“ Wear5”:0,“
Wear6”:0,“ Wear7”:0,“ Wear8”:0,“ standzeit1“:0,” standzeit2“:0,”
standzeit3“:0:” standzeit4“:0,” standzeit5“:0,” standzeit6“:0,”
standzeit7“:0,“ standzeit8”:0}]

新展品:

I / flutter(7654):W小工具库引起的异常CA ═════════════════════════I
/flutter(7654):构建MyHomePage(脏,状态:_MyHomePageState#9477b)时引发了以下RangeError:I /
flutter(7654):RangeError(索引):无效值:仅有效值为0:1 I / flutter(7654):I /
flutter(7654):引发异常时,这是堆栈:I / flutter( 7654):#0列表。[](dart:core / runtime /
libgrowable_array.dart:141:60)I / flutter(7654):#1
_MyHomePageState.createSeries(file:/// Users / Eti / AndroidStudioProjects /
test_json_app / lib / main.dart:71:35)I / flutter(7654):#2
_MyHomePageState.createChart(file:///Users/Eti/AndroidStudioProjects/test_json_app/lib/main.dart:89:7)I
/ flutter( 7654):#3
_MyHomePageState.build(文件:///Users/Eti/AndroidStudioProjects/test_json_app/lib/main.dart:57:58)I
/ flutter(7654):#4 StatefulElement.build(包:flutter / src / widgets /
framework.dart:3743:27) I / flutter(7654):#5
ComponentElement.performRebuild(package:flutter / src / widgets /
framework.dart:3655:15)I / flutter(7654):#6 Element.rebuild(package:flutter
/ src / widgets / framework.dart:3508:5)I / flutter(7654):#7
BuildOwner.buildScope(package:flutter / src / widgets /
framework.dart:2255:33)I / flutter(7654):#8
_WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&Renderer。
package:flutter / src / widgets / binding.dart:626:20)I / flutter(7654):#9
_WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&RendererBinding._handlePersistentFrameCallback(包:flutter
/ src / rendering / binding.dart:208:5)I / flutter(7654):#10
_WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback(package:flutter
/ src) / flutter(7654):#11
_WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame(package:flutter
/ src / scheduler / binding.dart:930:9)I / flutter(7654):#12
_WidgetsFlutterBinding&BindingBase&GestureBinding /
ServicesBinding&SchedulerBinding。 .dart:842:5)I / flutter(7654):#13
_invoke(dart:ui / hooks.dart:120:13)I / flutter(7654):#14 _drawFrame(dart:ui
/ hooks.dart:109 :3)I /flutter(7654):═════════════════════════════════════════
══════════════════════════════════════════════════ ═════════I /
flutter(7654):引发了另一个异常:RangeError(index):无效值:仅有效值为0:1 I /
flutter(7654):引发了另一个异常:RangeError(索引):无效值:仅有效值为0:1


阅读 295

收藏
2020-08-13

共1个答案

一尘不染

我认为您想要的是:

import 'dart:async';
import 'dart:convert';

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

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List data;
  Timer timer;

  makeRequest() async {
    var response = await http.get(
      'http://localhost/werkzeug/public/api/data_tool1',
      headers: {'Accept': 'application/json'},
    );

    setState(() {
      data = json.decode(response.body);
    });
  }

  @override
  void initState() {
    super.initState();
    timer = new Timer.periodic(new Duration(seconds: 2), (t) => makeRequest());
  }

  @override
  void dispose() {
    timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Tool Data'),
      ),
      body: data == null ? CircularProgressIndicator() : createChart(),
    );
  }

  charts.Series<LiveWerkzeuge, String> createSeries(String id, int i) {
    return charts.Series<LiveWerkzeuge, String>(
      id: id,
      domainFn: (LiveWerkzeuge wear, _) => wear.wsp,
      measureFn: (LiveWerkzeuge wear, _) => wear.belastung,
      // data is a List<LiveWerkzeuge> - extract the information from data
      // could use i as index - there isn't enough information in the question
      // map from 'data' to the series
      // this is a guess
      data: [
        LiveWerkzeuge('WSP1', data[i]['temp1']),
        LiveWerkzeuge('WSP2', data[i]['temp2']),
        LiveWerkzeuge('WSP3', data[i]['temp3']),
        LiveWerkzeuge('WSP4', data[i]['temp4']),
        LiveWerkzeuge('WSP5', data[i]['temp5']),
        LiveWerkzeuge('WSP6', data[i]['temp6']),
        LiveWerkzeuge('WSP7', data[i]['temp7']),
        LiveWerkzeuge('WSP8', data[i]['temp8']),
      ],
    );
  }

  Widget createChart() {
    // data is a List of Maps
    // each map contains at least temp1 (tool 1) and temp2 (tool 2)
    // what are the groupings?

    List<charts.Series<LiveWerkzeuge, String>> seriesList = [];

    for (int i = 0; i < data.length; i++) {
      String id = 'WZG${i + 1}';
      seriesList.add(createSeries(id, i));
    }

    return new charts.BarChart(
      seriesList,
      barGroupingType: charts.BarGroupingType.grouped,
    );
  }
}

class LiveWerkzeuge {
  final String wsp;
  final int belastung;

  LiveWerkzeuge(this.wsp, this.belastung);
}
2020-08-13