Search code examples
flutterdartflutter-getx

GetX - Passing Values Across ViewModels


I'm new to Getx & I'm trying to pass three String variables created in FirstViewModel into SecondViewModel how do I achieve this ?

class FirstViewModel extends GetxController with StateMixin<List<PhotoModel>> {...}
class SecondViewModel extends GetxController {...}

Solution

  • In your second viewmodel:

    class SecondViewModel extends GetxController {
         final FirstViewModel firstViewModel = Get.find();
    
         final firstString = Rxn<String>();
         
         final photoModels = <PhotoModel>[].obs;
    
    
       @override
       onInit(){
              firstString.value = firstViewModel.firstString.value; // If you are using Rx
    
              photoModels.assignAll(firstViewModel.state); // Get the state from `StateMixin`
    
     }