Search code examples
fluttergoogle-cloud-firestoreflutter-futurebuilder

Flutter hide button if it makes firebase document


I am trying to hide a button if a user has already submitted an item to firebase by using a future to check if the document id is not identical to the current user id, but the button is still appearing

_buildMakeOffer() {
    return FutureBuilder(
      future: DatabaseService.getOffer(
          task: widget.task!, currentUserId: widget.currentUserId),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const CircularProgressIndicator();
        }
        var offer = snapshot.data;
        print('Offer $offer');
        print('Curr ${widget.currentUserId}');
        if (!identical(offer.toString(), widget.currentUserId.toString())) {
          return ElevatedButton.icon(
              onPressed: () => Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (_) => MakeOffer(
                          currentUserId: widget.user!.id,
                          title: 'Make an Offer',
                          task: widget.task),
                      fullscreenDialog: true)),
              icon: const Icon(Icons.monetization_on_outlined),
              label: const Text('Make an Offer'));
        }

        if (snapshot.hasError) {
          return const Text('There is something wrong!');
        }

        return const SizedBox();
      },
    );
  }

When printing to console I can clearly see both IDs are matching so why is the button still present

flutter: Offer Jxav08McCnOopr0y7fOcKxYH3P13
flutter: Curr Jxav08McCnOopr0y7fOcKxYH3P13

Solution

  • That's because of how identical method works see https://api.dart.dev/stable/2.17.1/dart-core/identical.html

    the two String you provided to the this method are not identical because they are not the same object

    use != operator instead:

    final offer = snapshot.data as String;
    if (offer != widget.currentUserId) {
      return ElevetedButton();
    }