I am trying to render a simple 10×10 grid of characters on my application, but the grid boxes are not being rendered properly (only the characters are being displayed, not the boxes themselves), and I’m getting an exception stating: Null check operator used on a null value. I have tried using the late keyword, but that gives me the exception "LateInitializationError: Field ‘grid’ has not been initialized." Any ideas on how to get around this would really help. Thanks!
class _MyHomePageState extends State<MyHomePage> {
Grid? grid;
List<String> selectedList = [];
var isLoaded = true;
@override
void initState() {
// TODO: implement initState
getData();
super.initState();
}
getData() async{
grid = await RemoteService().getGrid();
if(grid!=null){
print('Payload received');
setState(() {
isLoaded = true;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Wordsearch'),
),
body: Visibility(
visible: isLoaded,
replacement: const Center(child: CircularProgressIndicator()),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
for(var i=0;i<10;i++) Row(
children: [
for(var j=0;j<10;j++) GridItem(
item: grid!.grid[i][j],
isSelected: (bool value){
setState(() {
if(value){
selectedList.add(grid!.grid[i][j]);
} else{
selectedList.remove(grid!.grid[i][j]);
}
});
})
],
)
],
)
),
);
}
}
2
Answers
Use a FutureBuilder to await the async request
https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html
Your Grid needs time to load, so if you run your build method immediatly, it will give you the null check error, because the grid is null.
I agree with targiasld, you should use a FutureBuilder if you are awaiting data.
Or if you want to await data and display after loaded, your grid assignment (i believe) needs to be in the setState call as well, and since you are doing that might as well use the grid having data to control visibility instead of a separate variable.
Also with your nested for loops i assume you are wanting a grid of widgets? There is a GridView widget which handles the building of the grid, which might fix the null checking.
I can provide code samples if that is needed