Hi guys I’m new to flutter . I was working with a follow along tutorial
and this were working out fine until I ran my code and got a null check operator used on a null value and when I remove the ! the code just stays on a loading mode and doesn’t return the response from thee api?
please advice
below is my main.dart
import 'package:flutter/material.dart';
import 'package:c3mobiredo/presentation/LoginScreen.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Material App',
home: Home(),
);
}
}
below is my LoginScreen.dart file
import 'package:flutter/material.dart';
import 'package:c3mobiredo/connectivity/apiConfig.dart';
import 'package:c3mobiredo/connectivity/models/getTimesheetForUserDay.dart';
import '../connectivity/Services/api_service.dart';
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
late List<UserProjectSpecificDay>? _userModel = [];
@override
void initState() {
super.initState();
_getData();
}
void _getData() async {
_userModel = (await ApiService().GetUserProjectSpecificDay())!;//where I'm getting the error but when I remove the ! the code stays in a loading state which is another issue
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('REST API Example'),
),
body: _userModel == null || _userModel!.isEmpty
? const Center(
child: CircularProgressIndicator(),
)
: ListView.builder(
itemCount: _userModel!.length,
itemBuilder: (context, index) {
return Card(
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(_userModel![index].id.toString()),
Text(_userModel![index].project.projectName),
],
),
const SizedBox(
height: 20.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(_userModel![index].hours),
Text(_userModel![index].desc),
],
),
],
),
);
},
),
);
}
}
2
Answers
since someone downvote, i update with reference from official documentation:
https://dart.dev/null-safety/understanding-null-safety
https://stackoverflow.com/a/69313493/12838877
and here you set the condition like that
here need to fix
non-null
variable and you will set the value later. removelate
when you initilizenullable
value.when you use
?
sign, it means, the variable isnullable
then on API call:
no need
!
anymore, because we had removelate
aboveIt means your reponse.body is null. You cn use use a FutureBuiler to build your widget and you can also set a timeout for the request after what you show the user that there is no data.
Eg: