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),
],
),
],
),
);
},
),
);
}
}
CodePudding user response:
It 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:
List<UserProjectSpecificDay>? _userModel;
bool isTimeout = false;
String errorMsg = '';
void _getData() async {
ApiService().GetUserProjectSpecificDay().then((response) {
// I suppose you have a "fromMap" in your model
if (response.statusCode == 200) {
var data = jsonDecode(response.body);
_userModel = UserProjectSpecificDay.fromMap(data);
} else if (response.statusCode == 408) {
setState(() {
isTimeout = true;
errorMsg = 'There was a network error';
});
} else setState(() => errorMsg = 'An error occured');
});
}
/* ... */
body: FutureBuilder(
builder: (_, __) {
if (_userModel != null) {
// return your widget
}
if (isTimeout) {
return Center(child: Text(errorMsg);
}
return Center(child: CircularProgressIndicator());
}
CodePudding user response:
since someone downvote, i update with reference from official documentation:
https://dart.dev/null-safety/understanding-null-safety
https://stackoverflow.com/a/69313493/12838877
when I remove the ! the code just stays on a loading mode yes it because your
_userModel == null
and here you set the condition like that
_userModel == null || _userModel!.isEmpty
? const Center(
child: CircularProgressIndicator(),)
here need to fix
- use late means, the value is
non-null
variable and you will set the value later. removelate
when you initilizenullable
value.
when you use ?
sign, it means, the variable is nullable
List<UserProjectSpecificDay>? _userModel; // since its nullable, no need to set initial value
then on API call:
void _getData() async {
_userModel = await ApiService().GetUserProjectSpecificDay());
}
no need !
anymore, because we had remove late
above
- last in your body:
body: _userModel == null // only check if null
? const Center(
child: CircularProgressIndicator(),)
: ListView.builder(
itemCount: _userModel.length ?? 0 // if null, set the list length = 0