flutterflutter-getxflutter-get

How can i pass value back using Get.back() from page2 to page1


Here are what i am trying

  1. Page 1 - Ask to select a value.
  2. Page 2 select the value from the list.
  3. Once value is selected, navigate back to Page 1
  4. the selected values should show in the page1.

a code snippet will help.


Solution

  • There may be a variety of different solutions...

    Here is one approach:

    see https://docs.flutter.dev/development/data-and-backend/state-mgmt/simple

    What you wrote could be a classic case for "Lifting State Up". You save the value in the parent widget of Page 1 and Page 2, the parent value is a stateful widget. You can pass the value and the handler (selecting the value) to page 1 and page 2 with the constructor (simplest solution). The "value" is stored in the parent widget (exactly: in the State object of the parent) as a state variable.


    ==== EDIT ====

    Sorry, never used GetX and just discovered that GetX state management has the concept of avoiding Stateful Widgets at all.... (don't work with the Flutter toolkit, let's fight it ;-)

    Maybe you can try according to this blog post, it shows you a simple solution: (without Obx) https://helloyogita.medium.com/flutter-state-management-with-getx-5b8cad6a33f7

    GetX uses GetxController classes to store the state vals.

    //----------
    /storing the state value
    class CounterController extends GetxController {
      int counter = 0;
    
      void increment() {
        counter++;
        modify();
      }
    }
    
    
    
    //---------------
    //setting the value in another widget
    
    
    final counterCtl = CounterController();
    ....
    onPressed: () { 
        counterCtl.increment();
        }
    
    
    
    //------------------
    //using the value
    
    class DemoGetBuilder extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return GetBuilder<CounterController>(
            init: CounterController(),
            builder: (controller) {
              return Text("Value = ${controller.counter}");
            });
      }
    }