[英]Flutter error : type Null is not a subtype of type 'String'
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:我在运行我的代码时遇到了这个错误,我正在尝试从 api 获取数据并将其显示到一个简单的小部件(中心)中,我正在发布整个代码 model 和屏幕代码以获取数据并将其显示到listview 只是为了看看这个方法是否有效(知道我已经为其他 model 尝试过它并且它有效)这是模型的代码:
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();
},
),
);
}
}
From从
horairePc: json["horaire_pc"],
To至
horairePc: json["horaire_pc"].toString(),
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. data 被标记为可空字段含义,数据可以是 null。 so while access data it will be a good idea to access with
?
因此,在访问数据时,使用 访问数据是个好主意
?
. .
idPc
also can be null. idPc
也可以是 null。 However a Text()
always expects a string field.但是
Text()
总是需要一个字符串字段。 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 eg Scaffold.使父页面成为
Scaffold
:目前您的屏幕显示全黑,因为没有可以在页面级别使用的适当的根小部件,例如 Scaffold。 Make you FutureBuilder
a child to Scaffold让你
FutureBuilder
成为 Scaffold 的孩子
DateTime.parse() in PlanningCoach: THe code datePc: DateTime.parse(json["date_pc"]),
will throw an excption if json["date_pc"]
is null. PlanningCoach 中的 DateTime.parse():代码
datePc: DateTime.parse(json["date_pc"]),
如果json["date_pc"]
为 null,将抛出异常。 so a better idea would be to check for null and then access.所以一个更好的主意是检查 null 然后访问。
if(json["date_pc"]) datePc: DateTime.parse(json["date_pc"])
Probably this is causing the null exception.这可能导致 null 异常。
perhaps the fact is that the name of the key is written in json not as "id_pc", but in a different way也许事实是密钥的名称写在 json 中,而不是“id_pc”,而是以不同的方式
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.