Rene Alas
Rene Alas

Reputation: 541

Running Async Code in factory Function in Flutter / Dart

I have this function using factory, (which to be honest I'm not sure why is needed, I just got it from a Tutorial, but is working the rest of the code).

This is the Function in question:

factory Listing.fromJason(Map<String, dynamic> data, String id) {
    List<String> images = [];

    data['photos'].forEach((photo) {
      images.add(photo);
    });

    return Listing(
      id: id,
      photos: images,
      price: double.parse(data['price'].toString()),
      status: data['status'],
      street: data['street'],
      street2: data['street2'],
      city: data['city'],
      state: data['state'],
      zipCode: int.parse(data['zipCode'].toString()),
      bedRooms: data['bedRooms'],
      bathRooms: data['bathRooms'],
      lotSize: data['lotSize'],
      schoolDistric: data['schoolDistric'],
      taxes: double.parse(data['taxes'].toString()),
      homeFeatures: data['homeFeatures'],
      floorPlans: data['floorPlans'],
      propertySurvey: data['propertySurvey'],
      yearBuilt: data['yearBuilt'],
      listingAgentName: data['listingAgentName'],
      listingAgentEmail: data['listingAgentEmail'],
      listingAgentPhone: data['listingAgentPhone'],
      dayStore: DateTime.parse(data['dayStore'].toDate().toString()),
      downPayment: data['downPayment'],
      county: data['county'],
      url: data['url'],
      listingType: data['listingType'],
      name: data['name'],
      username: data['username'],
      email: data['email'],
      imageUrl: data['image_url'],
      //isFavorite: favStat,
    );
  }

The Problem that I'm having is that I need to call inside of it this function to evaluate the Favorite Status:

Future<bool> isItFav(docId) async {
    final user = FirebaseAuth.instance.currentUser;
    final uid = user.uid;

    DocumentSnapshot favoriteSnapshot = await FirebaseFirestore.instance
        .doc('userfavorites/$uid/favorites/$docId')
        .get();

    bool result = favoriteSnapshot.exists;
    return result;
  }

The problem is that inside that function the one with the factory doesn't allow me to leave it as async or to put an await.

And I need to evaluate with the value of id (which I get as a parameter on top) if the document for that collection (the one on the isItFav function) exists and with that bool add it to the Listing object that I'm returning.

Any Ideas on what I can do.

Upvotes: 0

Views: 475

Answers (1)

jamesdlin
jamesdlin

Reputation: 90015

Just use a static method instead of a named factory constructor. A factory constructor offers no significant advantages in this case.

Upvotes: 1

Related Questions