I have scaffold with animated list that is dinamicaly constructed. It was working fine right before I tried to implement loading icon feature.
This function builds blocks of animated list
void _addItem(someItem) {
_items.insert(0, "${jsonEncode(someItem)} ");
_key.currentState!.insertItem(
0,
duration: const Duration(seconds: 1),
);
}
}
Now when I put small loading icon feature inside widget tree function fails to build saying _key.currentState is null.
This is my widget Tree
return Scaffold(
appBar: AppBar(
title: Text('app'),
automaticallyImplyLeading: false,
),
body: Container(
height: deviceSize.height,
width: deviceSize.width,
child:
_isShowLoadingIcon
? Image.asset('assets/images/Loading_icon.gif')
:
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded(
child: AnimatedList(
key: _key,
initialItemCount: 0,
padding: const EdgeInsets.all(10),
itemBuilder: (context, index, animation) {
return SizeTransition(
key: UniqueKey(),
sizeFactor: animation,
child: Card(
If we do not use
_isShowLoadingIcon ? Image.asset('assets/images/Loading_icon.gif') :
Then the rest of the code will work fine. How can I fix this problem ?
Added check for _isShowLoadingIcon
void _addItem(someItem) {
if (_isShowLoadingIcon) return;
print('_isShowLoadingIcon = ${_isShowLoadingIcon}');
_items.insert(0, "${jsonEncode(someItem)} ");
_key.currentState!.insertItem(
0,
duration: const Duration(seconds: 1),
);
}
}
App still crashing printing that _isShowLoadingIcon = false and then crash at line where _key.currentState is somehow null Null check operator used on a null value
I suspect that _key.currentState is null when you are showing the loading icon instead of the AnimatedList() with your _key. You might check if your key state is currently null before accessing ity, e. g.
void _addItem(someItem) {
if(_key.currentState == null) return;
_items.insert(0, "${jsonEncode(someItem)} ");
_key.currentState!.insertItem(0, duration: const Duration(seconds: 1));
}