fluttergoogle-cloud-firestorecustom-object

how to set custom object with document id to a collection in firestore in flutter?


I defined a dart class A with some string variables and a list of objects of another class B. I don't find any method function in cloud_firestore module to set this custom object of class A, as a document to the collection, even though custom objects are supported in Firestore. Do I need to convert all the members(strings, lists etc) of class A to JSON format or any other solution available?


Solution

  • In the event that it's inconvenient to create another collection of the related custom class, the only alternative is to build the related class instances yourself.

    import Player from // player module
    
    class GameState {
      constructor(data) {
        this.players = data.players.map(p => new Player(p))
        // ...
      }
    
      // flatten GameState into a generic JS map
      // build one of these on Player also
      asFBData() {
        const playerFBData = this.players.map(p => p.asFBData())
        return { playerFBData, ...other_game_state_here }
      }
    }
    
    const gameStateConverter = {
      toFirestore: gameState => gameState.asFBData(),
      fromFirestore: (snapshot, options) => new GameState(snapshot.data(options))
    }