Search code examples
fluttervariableschartsinstanceflutter-getx

unable to pass instance to the initializer


Error : The instance member 'widget' can't be accessed in an initializer.

Im creating a bar chart with getx controller, i want to retrieve values from firebase and pass it to barchart to show it to the user. But the main problem here is that the variable of string could not pass into the controller, can i have a guidance on how to pass it? none of the guidance help me, i really need the help

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:fyp/storage/OrderStats.dart';
import 'package:fyp/storage/OrderStatsController.dart';
import 'package:get/get.dart';

class testChart extends StatefulWidget {
  final String? salesDate;

  testChart({required this.salesDate});

  @override
  State<testChart> createState() => _testChartState();
}

class _testChartState extends State<testChart> {
  String sales = "11.2022 Sales";

  final OrderStatsController orderStatsController = Get.put(OrderStatsController(salesDate: '11.2022 Sales'));

  @override
  Widget build(BuildContext context) {
    return Scaffold(
     appBar: AppBar(
       title: Text('Bar Chart'),
     ),
      body: SizedBox(height: 300,
        child:
          FutureBuilder(
            future: orderStatsController.stats.value,
              builder: (BuildContext context, AsyncSnapshot<List<OrderStats>>
              snapshot){
              if(snapshot.hasData){
                return Container(
                  height: 250,
                  child: CustomBarChart(orderStats: snapshot.data!, sales: widget.salesDate.toString()),
                );
              }
              else if(snapshot.hasError){
                return Text('${snapshot.error}');
              }
              else{
                return Center(child: CircularProgressIndicator(),);
              }
              },
          )
        // CustomBarChart(orderStats: OrderStats.data,),
      ),
    );
  }
}

class CustomBarChart extends StatefulWidget {
  CustomBarChart({Key? key, required this.orderStats, required this.sales}) : super(key: key);
  final List<OrderStats> orderStats;
  final String sales;
  @override
  State<CustomBarChart> createState() => _CustomBarChartState();
}

class _CustomBarChartState extends State<CustomBarChart> {
  late String salesDate = '11.2022 Sales';

  final OrderStatsController orderStatsController = Get.put(OrderStatsController(salesDate: widget.sales.toString()));

  @override
  Widget build(BuildContext context) {
    List<charts.Series<OrderStats, String>> series = [
      charts.Series(
        id: 'sales',
        data: widget.orderStats,
        domainFn: (series, _) => series.serviceName.toString(),
        measureFn: (series, _) => series.sales,
      )
    ];
    return charts.BarChart(series, animate: true,);
  }
}


import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:fyp/storage/OrderStats.dart';
import 'package:get/get.dart';

import 'storageService.dart';


class OrderStatsController extends GetxController{
  final String salesDate;

  OrderStatsController({required this.salesDate});

  final Storage storage =  Storage();
  var stats = Future.value(<OrderStats>[]).obs;

  @override
  void onInit(){
    stats.value = FirebaseFirestore.instance.
    collection(salesDate).get().then((querySnapshot) =>
        querySnapshot.docs.asMap().entries.map((entry) =>
            OrderStats.fromSnapshot(entry.value, entry.key)).toList());
    super.onInit();
  }

}

right now i only tried passing just "sales", it is fixed, i cannot pass in any variable such as String type


Solution

  • You can define your controller like this:

    late OrderStatsController orderStatsController;
    

    then pass your value in initState :

    @override
      void initState() {
        super.initState();
    
        orderStatsController = Get.put(OrderStatsController(salesDate: sales));
      }