簡體   English   中英

Flutter 錯誤:類型 Null 不是“字符串”類型的子類型

[英]Flutter error : type Null is not a subtype of type 'String'

我在運行我的代碼時遇到了這個錯誤,我正在嘗試從 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"],
      );
}

這是獲取和顯示數據的代碼。

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();
        },
      ),
    );


}
}

這是錯誤: 錯誤

  horairePc: json["horaire_pc"],

  horairePc: json["horaire_pc"].toString(),

您的代碼中有幾個問題。 我會盡量多指點:

  1. 空安全用法:

     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 被標記為可空字段含義,數據可以是 null。 因此,在訪問數據時,使用 訪問數據是個好主意? . idPc也可以是 null。 但是Text()總是需要一個字符串字段。 將代碼更改為以下:

Text('${data?.elementAt(index).idPc ?? ''}') // if null use empty string
  1. 使父頁面成為Scaffold :目前您的屏幕顯示全黑,因為沒有可以在頁面級別使用的適當的根小部件,例如 Scaffold。 讓你FutureBuilder成為 Scaffold 的孩子

  2. PlanningCoach 中的 DateTime.parse():代碼datePc: DateTime.parse(json["date_pc"]),如果json["date_pc"]為 null,將拋出異常。 所以一個更好的主意是檢查 null 然后訪問。

     if(json["date_pc"]) datePc: DateTime.parse(json["date_pc"])

這可能導致 null 異常。

也許事實是密鑰的名稱寫在 json 中,而不是“id_pc”,而是以不同的方式

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM