I’m using StreamBuilder
and inside that, I have got a list of tasks which takes input from the snapshots and display the data accordingly, but I’m having a null safety issue when dealing with snapshot data. Here’s what the code looks like:
StreamBuilder<List<Task>>(
stream: DatabaseService()
.getCompletedTasks(orderName),
builder: (context, snapshot) {
List<Task> completedTasks =
snapshot.data!;
return snapshot.data!.isEmpty
? Container(
alignment:
Alignment.center,
child: Text(
"You don't have any completed tasks.",
style: TextStyle(
fontSize: 20,
fontFamily:
"Roboto",
color: Colors.black,
),
),
)
: Container(
child: Flexible(
flex: 0,
child: ListView
.separated(
physics:
const NeverScrollableScrollPhysics(),
shrinkWrap: true,
separatorBuilder:
(context,
index) =>
const SizedBox(
height: 5,
),
itemCount:
completedTasks
.length,
itemBuilder:
(context,
index) {
return Dismissible(
background:
Container(
color: Colors
.red,
child:
const Align(
alignment:
Alignment
.centerLeft,
child:
Padding(
padding:
EdgeInsets.all(
15.0),
child:
Icon(
Icons
.delete,
color: Colors
.white,
),
),
),
),
secondaryBackground:
Container(
color: Colors
.red,
child:
const Align(
alignment:
Alignment
.centerRight,
child:
Padding(
padding:
EdgeInsets.all(
15.0),
child:
Icon(
Icons
.delete,
color: Colors
.white,
),
),
),
),
key:
UniqueKey(),
onDismissed:
(direction) {
DatabaseService()
.deleteTask(
completedTasks[index]
.id);
AwesomeNotifications()
.cancelSchedule(
completedTasks[index]
.id);
},
child: Item(
task:
completedTasks[
index],
),
);
},
),
),
);
}),
Everything works fine but just null safety error pops up for a short amount of time.
2
Answers
Add 1 condition for while loading stream data on initial stage.
you force non null value here
add conditon like this