I have faced this error while running my code , I'm trying to fetch data from api and display it into a simple widget (Center ),I'm posting the whole code model and the screen's code to fetch data and display it into a listview just to see that this method is working (knowing that I've tried it for other model and it worked ) This is the model's code :
import 'package:meta/meta.dart';
import 'dart:convert';
class PlanningCoach {
final int? idPc;
final double? prixPc;
final DateTime? datePc;
final String? horairePc;
final int? nbpPc;
final int? idcoach;
final bool? recylcebin;
PlanningCoach({
required this.idPc,
required this.prixPc,
required this.datePc,
required this.horairePc,
required this.nbpPc,
required this.idcoach,
required this.recylcebin,
});
factory PlanningCoach.fromJson(Map<String, dynamic> json) => PlanningCoach(
idPc: json["id_pc"],
prixPc: json["prix_pc"],
datePc: DateTime.parse(json["date_pc"]),
horairePc: json["horaire_pc"],
nbpPc: json["nbp_pc"],
idcoach: json["idcoach"],
recylcebin: json["recylcebin"],
);
}
And this is code to fetch and display the data .
import 'dart:convert';
class DetailGroundScreen extends StatefulWidget {
const DetailGroundScreen({Key? key}) : super(key: key);
@override
_DetailGroundScreenState createState() => _DetailGroundScreenState();
}
class _DetailGroundScreenState extends State<DetailGroundScreen> {
late Future<List<PlanningCoach>> futurePCoach;
Future<List<PlanningCoach>> fetchPlanningCoach() async {
final response = await http.get(Uri.parse(
'http://smart.netrostercloud.com/smartcoach/api/plannningcoaches/displayPlanningCoach'));
if (response.statusCode == 200) {
List jsonResponse = json.decode(response.body);
return jsonResponse
.map((data) => new PlanningCoach.fromJson(data))
.toList();
} else {
throw Exception('Failed to load coach');
}
}
@override
void initState() {
//TODO : implement initState
super.initState();
futurePCoach = fetchPlanningCoach();
}
@override
Widget build(BuildContext context) {
final value = ModalRoute.of(context)!.settings.arguments;
// ignore: unnecessary_new
return Center(
child: FutureBuilder<List<PlanningCoach>>(
future: futurePCoach,
builder: (context, snapshot) {
if (snapshot.hasData) {
List<PlanningCoach>? data = snapshot.data;
return ListView.builder(
shrinkWrap: true,
itemCount: data?.length,
itemBuilder: (BuildContext context, int index) {
return Container(
height: 75,
color: Colors.white,
child: Center(
child: Text('${data![index].idPc}'),
),
);
});
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default show a loading spinner.
return CircularProgressIndicator();
},
),
);
}
}
CodePudding user response:
From
horairePc: json["horaire_pc"],
To
horairePc: json["horaire_pc"].toString(),
CodePudding user response:
You have couple of issues in your code. I will try pointing as many as I can:
Null-saftey usage:
List<PlanningCoach>? data = snapshot.data; return ListView.builder( shrinkWrap: true, itemCount: data?.length, itemBuilder: (BuildContext context, int index) { return Container( height: 75, color: Colors.white, child: Center( child: Text('${data![index].idPc}'), ), ); });
data is decalred as a nullable field meaning, data can be null. so while access data it will be a good idea to access with ?
. idPc
also can be null. However a Text()
always expects a string field. Change the code to below:
Text('${data?.elementAt(index).idPc ?? ''}') // if null use empty string
Make the parent most page a
Scaffold
: Currently your screen shows all black because there is no proper root widget that can be used at the page level e.g. Scaffold. Make youFutureBuilder
a child to ScaffoldDateTime.parse() in PlanningCoach: THe code
datePc: DateTime.parse(json["date_pc"]),
will throw an excption ifjson["date_pc"]
is null. so a better idea would be to check for null and then access.if(json["date_pc"]) datePc: DateTime.parse(json["date_pc"])
Probably this is causing the null exception.
CodePudding user response:
perhaps the fact is that the name of the key is written in json not as "id_pc", but in a different way