8

I would like to use context to show a custom dialog from cool alert in getxcontroller method. I have created the following controller

class HomePageController extends GetxController {
 
   @override
   void onInit() {
     super.onInit();
     getData();
   }

   void getData(){
    //perform http request here 
     //show cool alert 

     CoolAlert.show(
      context: context,  //here needs the build context
      type: CoolAlertType.success
      );
   }

}

Am using this controller in my stateless widget like

class HomePage extends StatelessWidget {
   HomePage({ Key? key }) : super(key: key);

   final _c = Get.find<HomePageController>();


    @override
    Widget build(BuildContext context) {
        return Container(
  
          );
    }
 }

How can i get the current homepage BuildContext in the controller inorder to show the cool alert.

Geoff
  • 6,277
  • 23
  • 87
  • 197

4 Answers4

2

If you want to show a dialog or snackbar what need context as a required agument. You can use Get.dialog() and Get.snackbar, there function work same as showDialog and showSnackbar but *without* context or scaffod

Tuan
  • 2,033
  • 1
  • 9
  • 16
1

You can simple use

Get.context

It will look like something like this

class HomePageController extends GetxController {
 
   @override
   void onInit() {
     super.onInit();
     getData();
   }

   void getData(){
    //perform http request here 
     //show cool alert 

     CoolAlert.show(
      context: Get.context,  //here needs the build context
      type: CoolAlertType.success
      );
   }

}
zaai
  • 71
  • 1
  • 2
0

you can add the context to the construct function:

@override
Widget build(BuildContext context) {
  Get.put(HomePageController(context: context));
  return Container();
}

and for the HomePageController:
note: you need to wrap the function with Future.delayed(Duration.zero) otherwise it will throw an error

class HomePageController extends GetxController {
  late BuildContext context;

  HomePageController({required this.context});
  
   void getData(){
     Future.delayed(Duration.zero,(){
       CoolAlert.show(
         context: context,  //here needs the build context
         type: CoolAlertType.success
       );
     });
   }
  ...
}

zrl
  • 19
  • 2
-3

You Need to Initialize the controller on the homepage like following

class HomePage extends StatelessWidget {
   HomePage({ Key? key }) : super(key: key);

   final _c = Get.put(HomePageController())..getData(context);


    @override
    Widget build(BuildContext context) {
        return Container(
  
          );
    }
 }

This will call getData Function and remove the onInit Function and Pass Buildcontext context parameter in getData Function.

MORE AKASH
  • 283
  • 1
  • 8