Home > OS >  how to display graph in flutter
how to display graph in flutter

Time:02-06

  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,
                      )
                    ]
                )
            )
        )
    );
  }
}

I want to retrieve data from firestore where I create GraphModel but i dont know to declare from firebase to input in the graph. Please help me how to declare this graph

CodePudding user response:

need to import the cloud_firestore package to your pubspec.yaml file

Heres the full code to retrieve data from 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,
              ),
            ],
          ),
        ),
      ),
    );
  }
}
  • Related