xpetta
xpetta

Reputation: 718

Flutter: type 'Future<bool>' is not a subtype of type 'bool' in type cast

I'm trying to display a widget based on the value returned. But getting the below error.

type 'Future<bool>' is not a subtype of type 'bool' in type cast

Here is the source code which is causing the error:

  Future<bool> fetchCourses() async {
    List courses = [];
    final loggedInUser = FirebaseAuth.instance.currentUser;
    if (loggedInUser != null) {
      final userCollection = await FirebaseFirestore.instance.collection('users').doc(loggedInUser.uid).get();
      courses = userCollection.get('coursesEnrolled');
    }
    if (courses.length == 0) {
      return false;
    } else {
      return true;
    }
  }
.
.
.
bool hasCourses = fetchCourses() as bool;
.
.
.
hasCourses ? ListAllUserEnrolledCourses() : Container(),

Upvotes: 2

Views: 3563

Answers (2)

Tirth Patel
Tirth Patel

Reputation: 5736

fetchCourses() returns a Future<bool>, use FutureBuilder to resolve the Future.

FutureBuilder<bool>(
  future: fetchCourses(),
  builder: (_, snapshot) {
    if (snapshot.hasData) {
      return snapshot.data ? ListAllUserEnrolledCourses() : Container();
    }
    return Text('Loading...');
  },
),

Upvotes: 2

Huthaifa Muayyad
Huthaifa Muayyad

Reputation: 12353

bool hasCourses = await fetchCourses();

You need to await for it to finish, but no need to cast it.

Upvotes: 2

Related Questions