Home > front end >  how initialize variable in GetX controller?
how initialize variable in GetX controller?

Time:11-18

hi I have Get x Controller with the late Map data and I want fill this in onInit after search on database, but when the page is open the emulator show the red screen with the not initialize error. I need the dataMap1 and 2 for show the PieChart when the screen open. I Think this is occurred because I use the Future function, But I do not now how to fix this.
this is my entire controller code.

import 'package:get/get.dart';
import 'package:hive/hive.dart';

class ReportScreenController extends GetxController{

   late Map<String, double> dataMap1;

  final Map<String, double> dataMap2 = {
    "ورزشی": 5,
    "خصوصی": 3,
    "اداری": 5,
    "دسته بندی نشده": 3,
  };

  @override
  Future<void> onInit() async {
    super.onInit();
    //categoryScrollController.position.ensureVisible()
    await reportFunction();
  }

  Future<void> reportFunction() async {
    //dataMap1
    var taskBox = await Hive.openBox('task');
    var taskFinish =
    taskBox.values.where((task) => task.status == true).toList();

    var taskUnFinish =
    taskBox.values.where((task) => task.status == false).toList();
    double test = double.parse(taskFinish.length.toString());
    double test2 = double.parse(taskUnFinish.length.toString());
    print(test.toString());
    print(test2.toString());
    dataMap1.addAll({
      'رو زمین مانده': test2,
      'تکمیل شده': test,
    });
  }
}

my view code is

class ReportScreen extends GetView<ReportScreenController> {
  const ReportScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        fit: StackFit.expand,
        children: [
          background(),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 15.0),
            child: Column(
              children: [
                const Text(':نمودار فعالیت', style: boldText),
                MyPieChart(dataMap: controller.dataMap1),
                const Text(':نمودار وظایف', style: boldText),
                MyPieChart(dataMap: controller.dataMap2),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

CodePudding user response:

You forgot to initialize dataMap1, simply in onInit() add dataMap1 = {}. I think you also dont need a late modifier, just use final final Map<String, double> dataMap1 = {};, but everybody is choosing thier weapons.

In addition i think there will be problem with that how you use controller.dataMap1 in your view. Most likely you dont rebuild your view after you finally initialize / populate dataMap1.

Update:

You can change in controller: late Map<String, double> dataMap1; to final RxMap<String, double> dataMap1 = RxMap();, and in your view:

MyPieChart(dataMap: controller.dataMap1), to Obx(() => MyPieChart(dataMap: controller.dataMap1.value))

  • Related