Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To obtain the current page context in a Flutter GetX controller:

  1. Import the Get package:

    import 'package:get/get.dart';
    
  2. Access the current page context using Get.context:

    class MyController extends GetxController {
     void doSomethingWithCurrentPage() {
       // Access the current page context
       if (Get.context != null) {
         print("Current page context: ${Get.context}");
       }
     }
    }
    

    Note: It's important to check if Get.context is not null before accessing it to avoid errors.

  3. Call the doSomethingWithCurrentPage method from the widget that contains the current page context:

    class MyPage extends StatelessWidget {
     final MyController controller = Get.put(MyController());
    
     @override
     Widget build(BuildContext context) {
       return Scaffold(
         body: Center(
           child: ElevatedButton(
             child: Text("Do something"),
             onPressed: () {
               // Call the controller method to access the current page context
               controller.doSomethingWithCurrentPage();
             },
           ),
         ),
       );
     }
    }