I have below code in flutter which shows the list of the names with rank.
All are working fine but I want to access the first character of the lastName
. When I do this, throws the error Bad State: No element
.
class ThisMonthTab extends StatelessWidget {
const ThisMonthTab({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 10),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Expanded(
child: StreamBuilder<List<UserModel>>(
stream: PlayersRepo.fetchThisMonthPlayersList(),
builder: (context, snapshot) {
List<UserModel>? list = snapshot.data;
if (snapshot.connectionState == ConnectionState.waiting) {
return getLoader();
}
if (snapshot.data!.isEmpty) {
return emptyPageMessage(
LocaleKeys.noProgressThisMonth.tr());
}
if (snapshot.hasData) {
log(snapshot.data!.length.toString());
return ListView.builder(
shrinkWrap: true,
itemCount: list?.length,
padding: const EdgeInsets.only(top: 10),
itemBuilder: (context, index) => LeaderboardTileWidget(
imageUrl: list![index].avatarUrl,
title:
'${list[index].firstName} ${list[index].lastName.characters.first}.', //Error is here in this line for accessing the first character of last name
subtitle:
'${LocaleKeys.level.tr()} ${list[index].currentLevel} (${list[index].currentRankName.characters.first}), ${list[index].monthlyXP.gainedXP} XP',
isUser: list[index].id ==
context.read<UserModelProvider>().user.email,
rankNo: index + 1,
),
);
} else {
return emptyPageMessage(LocaleKeys.fetchError.tr());
}
}),
),
const SizedBox(height: 10),
Text(
LocaleKeys.leaderboardDescription.tr(),
style: Theme.of(context).textTheme.subtitle1?.copyWith(
fontSize: 9, color: Colors.grey.shade600, letterSpacing: 0.4),
),
const SizedBox(height: 70)
],
),
);
}
}
Can anyone figure out what is the mistake here because directly if I am displaying the list[index].lastName
it works totally fine.
2
Answers
I have just solved the error by checking if
lastName is Empty or Not
. In the list of the names it was broken where the names does not have last name.I have changed
list[index].lastName.characters.first
tolist[index].lastName.isEmpty ? " " : list[index].lastName.characters.first
Hope this helps someone.
If you just want the first character of the last name, why not go the JS way, just change
list[index].lastName.characters.first
to
list[index].lastName[0]
For safe bet, you may want to convert it to
String
first aslist[index].lastName.toString()[0]
The reasoning is, at the EOD, a
String
is just anArray
ofCharacters
and by[0]
, we’re picking its first item. You can run and check this at the Dart Playground.