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

Time:12-05

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

CodePudding user response:

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);
  • Related