Home > Mobile >  How to fix Lateinitializationerror in flutter
How to fix Lateinitializationerror in flutter

Time:10-11

I have a minor bug in my flutter app, it is trying to display a chart of users but before it does it will first display Lateinitializationerror. But then after a few seconds it runs the way I want it to be. How can I fix that bug? Here is my code.

class _AdminDashboardState extends State<AdminDashboard> {
  late List<USERdata>? _chartData;
  late TooltipBehavior _tooltipbehaviorpie;

  @override
  void initState() {
    getDataFromDatabase().then((value) {
      _chartData = getChartData();
      _tooltipbehaviorpie = TooltipBehavior(enable: true);
    }).whenComplete(() => setState(
          () {},
        ));
    super.initState();
  }

  
  var mentor_count;
  var incubate_count;

  Future getDataFromDatabase() async {
    final CollectionReference collectionRefIncubate =
        FirebaseFirestore.instance.collection('incubatees');
    QuerySnapshot querySnapshotIncubate = await collectionRefIncubate.get();
    final length1 = querySnapshotIncubate.docs.length;
    incubate_count = length1;
    final CollectionReference collectionRefMentor =
        FirebaseFirestore.instance.collection('mentors');
    QuerySnapshot querySnapshotMentor = await collectionRefMentor.get();
    final length2 = querySnapshotMentor.docs.length;
    mentor_count = length2;
  }

  @override
  Widget build(BuildContext context) {
    //users chart
    final userData = Container(
      decoration: BoxDecoration(border: Border.all(color: Colors.black)),
      margin: const EdgeInsets.symmetric(horizontal: 20),
      height: MediaQuery.of(context).size.height * 0.30,
      child: SfCircularChart(
        title: ChartTitle(text: 'Users\n(Mentors & Incubates)'),
        legend: Legend(
          isVisible: true,
          overflowMode: LegendItemOverflowMode.wrap,
        ),
        tooltipBehavior: _tooltipbehaviorpie,
        series: <CircularSeries>[
          PieSeries<USERdata, String>(
            dataSource: _chartData,
            xValueMapper: (USERdata data, _) => data.user,
            yValueMapper: (USERdata data, _) => data.count,
            dataLabelSettings: const DataLabelSettings(
              isVisible: true,
              labelAlignment: ChartDataLabelAlignment.top,
            ),
            enableTooltip: true,
            // maximumValue: 40000,
          )
        ],
      ),
    );

    return SafeArea(
        child: Scaffold(
            appBar: AppBar(
              title: const Text("Dashboard"),
              centerTitle: true,
            ),
            body: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  userData,
                ],
              ),
            )));
  }

  List<USERdata> getChartData() {
    final List<USERdata> chartData = [
      USERdata('Mentors', mentor_count),
      USERdata('Incubatees', incubate_count),
    ];
    return chartData;
  }
}

I created late initializations first that will be used for my pie chart, and called the initstate to put them values. The error occurs after I hot restart, but a few seconds after that, it runs the way I want them to be. Is there a way on how to fix this bug?

CodePudding user response:

In this case you should change your late variable to nullable variable:

List<USERdata>? _chartData;
TooltipBehavior? _tooltipbehaviorpie;

and in your build method, check:

 @override
  Widget build(BuildContext context) {
    if (_chartData == null || _tooltipbehaviorpie == null) {
       return const SizedBox();   //may be change your loading widget here
    }
    
    // from here you can use _chartData! and tooltipbehaviorpie!

    return yourWidget();
  }
  • Related