Home > database >  Flutter type 'Future<dynamic>' is not a subtype of type 'Widget' error
Flutter type 'Future<dynamic>' is not a subtype of type 'Widget' error

Time:12-19

what I want to do is to pull some data from the docs where the logged in user is email from the collection named Repair. I created a function for this. But I'm getting the - type 'Future' is not a subtype of type 'Widget' - error.

getCustomerRepairLog() async {
    final user = FirebaseAuth.instance.currentUser!;
    var _repairLogs = await FirebaseFirestore.instance.collection('Repair').get();
    for (var eleman in _repairLogs.docs) {
      if (eleman.data()['email']! == user.email) {
        return Container(
          child: Column(
            children: [
              Text("$eleman.data()['description']"),
            ],
          ),
        );
      }
    }
    return Text('Loading');
  }

I want to use it as getCustomerRepairLog() in Column. Can you help me?

CodePudding user response:

You need to use FutureBuilder for future method.Create state variable to avoid recalling evrytime the state is build.

final user = FirebaseAuth.instance.currentUser!; //better do a null check 1st
late final _repairLogs = FirebaseFirestore.instance.collection('Repair').get();

And your method will be like

  Widget getCustomerRepairLog() {
    return FutureBuilder(
      future: _repairLogs,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          List<Widget> items = [];
          final data = snapshot.data?.docs;
          if (data == null) return Text("got null");

          for (final eleman in data) {
            if (eleman.data()['email']! == user.email) {
              items.add(Text("${eleman.data()['description']}"));
            }
          }
        return CircularProgressIndicator();
      },
    );
  }

Find more about FutureBuilder

  • Related