Home > Software engineering >  How to append into 1 data
How to append into 1 data

Time:03-11

I have this code where it will write in the firebase for email and name. Then the timers written in the firebase multiple times. I wanted to do it so that it would only write 1 time for all. How can I append the timers in the data variable so that I can write it in firebase in one go.

DocumentReference<Map<String, dynamic>> ref =
    db.collection(Paths.usersPath).doc(uid);
var data = {
  'email': email,
  'name': name,
};
ref.set(data, SetOptions(merge: true));

for (int i = 1; i <= 5; i  ) {
  await db.collection(Paths.usersPath).doc(uid).set({
    'timers': {
      'timePos$i': {
        'Time01': Timestamp.fromDate(DateTime.now()),
        'Time02': Timestamp.fromDate(DateTime.now()),
        'Time03': Timestamp.fromDate(DateTime.now()),
        'Time04': Timestamp.fromDate(DateTime.now()),
        'Time05': Timestamp.fromDate(DateTime.now()),
      },
    },
  }, SetOptions(merge: true));
}

CodePudding user response:

Maybe you could first build your data and then set it at once.

final nbTimers = 5;
final nbPositions = 5;

// Build your data
final data = {
  'email': email,
  'name': name,
  'timers': Map.fromIterable(
    List<int>.generate(nbTimers, (i) => i   1),
    key: (t) => 'timePos$t',
    value: (t) => Map.fromIterable(
      List<int>.generate(nbPositions, (i) => i   1),
      key: (p) => 'Time0$p',
        value: (p) => Timestamp.fromDate(DateTime.now()),
    )
  )
};

// Set your data to Firebase
DocumentReference<Map<String, dynamic>> ref = db.collection(Paths.usersPath).doc(uid);
ref.set(data, SetOptions(merge: true));
  • Related