Flutter中图形显示方法

6ojccjat  于 2023-02-09  发布在  Flutter
关注(0)|答案(1)|浏览(122)
Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
            child: Container(
                child: SfCartesianChart(
                  // Enables the legend
                    legend: Legend(isVisible: true),
                    // Initialize category axis
                    primaryXAxis: CategoryAxis(),
                    series: <ChartSeries>[
                      // Initialize line series
                      LineSeries<GraphModel, String>(
                        dataSource: [
                          // Bind data source
                          // retrieve data from database
                          GraphModel(
                              productName: ['prodName'], count: 'count'.length

                          ),
                        ],
                        xValueMapper: (GraphModel data, _) => data.productName,
                        yValueMapper: (GraphModel data, _) => data.count,
                      )
                    ]
                )
            )
        )
    );
  }
}

我想从创建GraphModel的firestore中检索数据,但我不知道如何声明从firebase到图中的输入。请帮助我如何声明此图

juzqafwq

juzqafwq1#

我需要将cloud_firestore软件包导入到pubspec.yaml文件中
下面是从firestore检索数据的完整代码:

import 'package:cloud_firestore/cloud_firestore.dart';

class GraphModel {
  String productName;
  int count;

  GraphModel({this.productName, this.count});
}

class YourWidget extends StatefulWidget {
  @override
  _YourWidgetState createState() => _YourWidgetState();
}

class _YourWidgetState extends State<YourWidget> {
  List<GraphModel> _graphData = [];

  @override
  void initState() {
    super.initState();
    _retrieveDataFromFirestore();
  }

  void _retrieveDataFromFirestore() async {
    final firestore = FirebaseFirestore.instance;
    final graphData = await firestore.collection('your_collection').get();

    setState(() {
      _graphData = graphData.docs.map((doc) => GraphModel(
        productName: doc.data()['product_name'],
        count: doc.data()['count'],
      )).toList();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          child: SfCartesianChart(
            legend: Legend(isVisible: true),
            primaryXAxis: CategoryAxis(),
            series: <ChartSeries>[
              LineSeries<GraphModel, String>(
                dataSource: _graphData,
                xValueMapper: (GraphModel data, _) => data.productName,
                yValueMapper: (GraphModel data, _) => data.count,
              ),
            ],
          ),
        ),
      ),
    );
  }
}

相关问题