mardi 24 mars 2020

Using Flutter Checkbox() and obtaining initial value from Firestore

I'm no experienced programmer and I could find no guidance, hence this question. I have a working solution but not sure if this is good practice.

I am using the widget Checkbox() in a Form(). Widgets like TextFormField() and DateTimeField() have a parameter called 'initialValue'. Checkbox() does not.

For TextFormField() and DateTimeField() I obtained the initialValue by:

@override Widget build(BuildContext context) { final user = Provider.of(context);

return StreamBuilder<UnitDetails>(
  stream: DatabaseServices(uid: user.userUid, unitUid: widget.unitUid)
      .unitByDocumentID,
  builder: (context, unitDetails) {
    if (!unitDetails.hasData) return Loading();
    return Scaffold(
    etc

The Checkbox(value: residentialUnit,) can not have its initial value set inside the builder:. The parameter 'value:' needs to be set true or false before the builder: ie before the value is obtained from Firestore! The way I solved this is by using initState(). An extra call to Firestore and more code for this one input widget.

@override void initState() { super.initState();

Firestore.instance
    .collection("units")
    .document(widget.unitUid)
    .snapshots()
    .listen((snapshot) {
  residentialUnit = snapshot.data['unitResidential'];
});

}

Is there a better way?




Aucun commentaire:

Enregistrer un commentaire