I'm trying to create a DropDownButton using the data from a table. I've created a function to return a list of objects which then can be used to convert those to a list of string but I keep getting "Null check operator used on a null value" error. So I tried to remove as many exclamation mark as I can. But I'm still getting the same error.
This is the function I use to get the list of objects from the DatabaseHelper class.
Future<List<Category>> getCategories() async {
Database? db = await instance.database;
var categories = await db?.query('Category', orderBy: 'id');
List<Category> categoryList = categories!.isNotEmpty ? categories.map((c) =>
Category.fromMap(c)).toList(): [];
return categoryList;
}
This is the FutureBuilder and the DropDropButton
child: FutureBuilder<List<Category>> (
future: DatabaseHelper.instance.getCategories(),
builder: (BuildContext context, AsyncSnapshot<List<Category>> snapshot) {
if (!snapshot.hasData) {
return const Text('No data');
}
else {
return DropdownButton(
onChanged: (value) { },
items: snapshot.data?.map((category) =>
DropdownMenuItem<String>(
value: category.categoryName,
child: Text(category.categoryName),
)
).toList(),
);
}
},
)
CodePudding user response:
Please change categories!.isNotEmpty
to categories?.isNotEmpty
CodePudding user response:
For some reason categories
is null, i.e it's not properly fetched from the database. So this is leading to invoke isNotEmpty
on a null value i.e null.isNotEmpty
which is wrong, so the above error.
To overcome this , dont use the isNotEmpty
property
Use something like :
List<Category> categoryList = categories ? categories.map((c) =>
Category.fromMap(c)).toList(): [];
CodePudding user response:
Setting the isExpanded to true solves my problem.