Home > Back-end >  How to create a DropMenuItem from Future list in flutter?
How to create a DropMenuItem from Future list in flutter?

Time:12-04

I am getting a data from local database using floor in flutter. And I want to display the list of doctors from the db I am using DropDownButton to do this This is my code

DropdownButton(
                icon: const Icon(
                  Icons.arrow_drop_down,
                ),
                hint: const Text('Select a doctor'),
                items: FutureBuilder<List<Doctor>>(
                    future: findAllDoctor(),
                    builder: (context, snapshot) {
                      if (snapshot.hasData) {
                        return snapshot.data
                            .map((doctor) => DropdownMenuItem(
                                  child: Text(doctor.name),
                                  value: doctor,
                                ))
                            .toList();
                      } else if (snapshot.hasError) {
                        return Text("${snapshot.error}");
                      }
                      return CircularProgressIndicator();
                    }
                ), ,
                onChanged: (val) {
          print(val);
          },
          ),

And this is how I get the data

Future<List<Doctor>> findAllDoctor() async {
    return await database.doctorDao.findAllDoctor();
  }

I am getting this error

The argument type 'FutureBuilder<List<Doctor>>' can't be assigned to the parameter type 'List<DropdownMenuItem<Object>>?'.

What I need here is to display the doctors as list in a form to choose from.

CodePudding user response:

Your FutureBuilder was placed in wrong place, check my edited code:

FutureBuilder<List<Doctor>>(
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return DropdownButton<String>(
        icon: const Icon(
          Icons.arrow_drop_down,
        ),
        hint: const Text('Select a doctor'),
        items: snapshot.data
            ?.map((doctor) => DropdownMenuItem(
                  child: Text(doctor.name),
                  value: doctor.name,
                ))
            .toList(),
        onChanged: (val) {
          print(val);
        },
      );
    } else if (snapshot.hasError) {
      return Text("${snapshot.error}");
    }
    return const CircularProgressIndicator();
  },
);
  • Related