Диаграммы флаттера с помощью Api Json

#android #flutter #dart #flutter-layout #flutter-web

Вопрос:

Я использую API JSON для создания линейной диаграммы в своем приложении. Вывод API был

 [{"date":"2021-09-03","price":"29490"},
{"date":"2021-09-04","price":"29490"},
{"date":"2021-09-05","price":"29490"},
{"date":"2021-09-06","price":"29490"}]
 

теперь мой новый вывод JSON в этом формате

 [{"2021-09-01":"23200","2021-09-02":"23200","2021-09-03":"23200","2021-09-04":"23200"}]
 

Может кто-нибудь, пожалуйста, дайте мне знать, какие изменения мне нужно внести в код Flutter, чтобы он работал .

                Future<String> getJsonFromFirebase(productasin) async {
              String url = "https://example.com/chart.json";
              http.Response response =
              await http.post(Uri.parse(url), body: {'productchart': productasin});
              return response.body;
                 }

            Future loadSalesData() async {
            final String jsonString = await getJsonFromFirebase(productasin);
            final dynamic jsonResponse = json.decode(jsonString);
            for (Map<String, dynamic> i in jsonResponse)
            chartData.add(SalesData.fromJson(i));
               }

                class SalesData {
               SalesData(this.date, this.price);

              final String date;
              final double price;

             factory SalesData.fromJson(Map<String, dynamic> parsedJson) {
             return SalesData(
             parsedJson['date'].toString(), double.parse(parsedJson['price']));
              }
              }
               



                             child: FutureBuilder(
                future: getJsonFromFirebase(productasin),
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    loadSalesData();
                    return SfCartesianChart(
                        trackballBehavior: _trackballBehavior,
                        primaryXAxis: CategoryAxis(
                          //Hide the gridlines of x-axis
                          majorGridLines: MajorGridLines(width: 0),
                          //Hide the axis line of x-axis
                          axisLine: AxisLine(width: 0),
                        ),
                        primaryYAxis: NumericAxis(
                            edgeLabelPlacement: EdgeLabelPlacement.shift,
                            //Hide the gridlines of y-axis
                            majorGridLines: MajorGridLines(width: 0),
                            //Hide the axis line of y-axis
                            axisLine: AxisLine(width: 0)),
                        tooltipBehavior: _tooltipBehavior,
                        series: <ChartSeries<SalesData, String>>[
                          StackedAreaSeries<SalesData, String>(
                              dataLabelSettings: DataLabelSettings(
                                isVisible: true,
                                labelAlignment: ChartDataLabelAlignment.top,
                                useSeriesColor: true,
                                showCumulativeValues: true,
                              ),
                              name: 'Price',
                              dataSource: chartData,
                              borderColor: Colors.white,
                              borderWidth: 2,
                              xValueMapper: (SalesData sales, _) =>
                                  sales.date,
                              yValueMapper: (SalesData sales, _) =>
                                  sales.price,
                              markerSettings:
                                  MarkerSettings(isVisible: true)
                              //gradient: gradientColors
                              )
                        ]);
                  } else {
                    return Center(child: CircularProgressIndicator());
                  }
                })),
 

Ответ №1:

Эта единственная строка может помочь вам

 jsonResponse[0].forEach((k, v) =>   chartData.add(SalesData(k, Double.tryParse(v)); );