简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM