Couldn't insert age in firestore in flutter

Viewed 29

I got the age from date I date picker . And also age display corerctly but I couldn't insert in firestore, when I click the submit button then show this error.

enter image description here

code

 DateDuration? duration;

  void calAge() {
    DateTime? birthday = selectedDate;

    duration = AgeCalculator.age(birthday!);
    print('Your age is $duration');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        margin: EdgeInsets.all(40),
        width: double.infinity,
        height: MediaQuery.of(context).size.height * 0.25,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            ElevatedButton(
              child: Text("Show DatePicker"),
              onPressed: () {
                showDatePicker();
              },
            ),
            Text(selectedDate == null ? "" : "$selectedDate"),
            Text(selectedDate == null ? "" : "$duration"),
            ElevatedButton(
              onPressed: () {
                send();
              },
              child: const Text("submit"),
            ),
          ],
        ),
      ),
    );
  }

  void send() {
    Map<String, dynamic> data = {
      "field5": selectedDate,
    };
    FirebaseFirestore.instance.collection("data").doc().set({
      "field5": selectedDate,
      "field6": duration,
    });
  }
}

enter image description here

1 Answers

DateDuration is not a Supported Datatype in Firebase.

What you can to is store the dateTime as int:

To store use:

int dateAsInt = yourDateTime. millisecondsSinceEpoch;

And when retrieving it you an convert the int back to DateTime like this:

DateTime date = DateTime.fromMillisecondsSinceEpoch(yourDateTimeAsInt);
Related