Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter getx controller get the current page context

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.

like image 818
Geoff Avatar asked May 26 '26 00:05

Geoff


2 Answers

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

}
like image 88
zaai Avatar answered May 28 '26 13:05

zaai


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

like image 32
Tuan Avatar answered May 28 '26 15:05

Tuan