I'm trying to check the number of columns a Wrap widget creates on screen, I wrote this code:
late double _charsWidth;
late int _numberOfColumns;
@override
void initState() {
//_scrollController.jumpTo(0);
_charsWidth = widget.characters.length * 100;
WidgetsBinding.instance?.addPostFrameCallback((_) {
final RenderBox renderBox =
_containerKey.currentContext?.findRenderObject() as RenderBox;
print('_charsWidth: $_charsWidth');
print('renderBox.size.width: ${renderBox.size.width}');
setState(() {
_numberOfColumns = (renderBox.size.width / _charsWidth).ceil();
});
super.initState();
print(_numberOfColumns); // error
});
But I'm getting an error LateInitializationError: Field '_numberOfColumns@45197325' has not been initialized.
with print(_numberOfColumns)
.
What's the correct way of updating the state here?
CodePudding user response:
remove the late keyword, avoid using late keyword before null-able variable
double? _charsWidth;
int? _numberOfColumns;