Search code examples
flutterdartflutter-getx

How to make a copy of a object retrieved from Get.find in flutter


I have a class named GameData and put it in the memory using Get.put. I need to make a copy of this class in a variable, such that whenever I change data in the variable, the instance in the memory isn't affected.

The reason i need to do this is because GameData is a class that holds data that is used by many other classes, And i want to create a copy of it that DOES NOT point to the object in memory


Solution

  • Use the .copyWith method on GameData class:

    class GameData{
      ...
      SomeType gameBoard;
    
      GameData copyWith(
       ....,
       SomeType? gameBoard,
     ) {
       return GameData(
        ...,
        this.gameBoard: gameBoard?? this.gameBoard,
       );
      }
        
    }
    

    Then copy the instance with updated value of gameBoard like:

    final copiedInstance= Get.find<GameData>().copyWith(gameBoard: updatedGameBoardValue);