請幫幫我...幾天以來我一直試圖解決這個問題,但沒有任何效果TT
我有一個資料庫 phpmyadmin
我想顯示一個由 php url 傳遞的 json 串列。我試圖調整這段代碼,https://www.fluttercampus.com/guide/53/how-to-make-drop-down-and-insert-options-by-php-mysql-in-flutter/ 但我有這個錯誤
在構建 AddTimePage(dirty, dependencies: [MediaQuery], state: AddTimeState#1a618) 時引發了以下 NoSuchMethodError:在 null 上呼叫了方法“[]”。接收者:null 嘗試呼叫:
我不明白什么是 null 或 [] ... 我收到的 json 是好的
我獲取資料的功能
Future<dynamic> getTypeTemps() async {
var res = await http.post(Uri.parse(TTurl "?action=LST"));
if (res.statusCode == 200) {
setState(() {
TTdata = json.decode(res.body);
});
} else {
setState(() {error = true; message = "Erreur avec la table TypeTemps";});
} }
getTypeTemps 在 void initstate() 中呼叫
顯示串列的小部件
Widget WdgListTT() {
List<TypesTemps> ttlist = List<TypesTemps>.from(
TTdata["TTdata"].map((i){
return TypesTemps.fromJSON(i);
})
); //searilize typetemps json data to object model.
return Column(children: [
const Padding(
padding: EdgeInsets.only(bottom: 20),
),
SizedBox(
width: MediaQuery.of(context).size.width - 40,
child: const Text("Type de temps", style: TextStyle(color: Colors.teal, fontWeight: FontWeight.bold, fontSize: 18),),
),
SizedBox(
width: MediaQuery.of(context).size.width - 50,
child: DropdownButtonHideUnderline(
child: DropdownButton<String>(
//style: const TextStyle(color: Colors.white),
value: valtypetemps,
onChanged: (value) => setState(() => valtypetemps = value),
elevation: 20,
underline: Container(
height: 10,
color: Colors.red,
),
hint: const Text("Sélectionnez un type",
style: TextStyle(fontSize: 16)),
isExpanded: true,
items: ttlist.map((typesTemps) {
return DropdownMenuItem(
child: Text(typesTemps.libelle,
style: TextStyle(color: Colors.black)),
value: typesTemps.libelle,
);
}).toList(),
)))
]); }
班上
class TypesTemps { String code, libelle, type_temps; TypesTemps({
required this.code,
required this.libelle,
required this.type_temps, }); factory TypesTemps.fromJSON(Map json) {
return TypesTemps(
code: json["CODE"],
libelle: json["LIBELLE"],
type_temps: json["SENS_TYPE_TEMPS"]); } }
uj5u.com熱心網友回復:
這是您的問題:您有一張名為TTdata. 這張地圖開始沒有價值。然后 initstate 運行,它呼叫getTypeTemps. 終于build跑了。其中有這一行:
TTdata["TTdata"].map((i){
這一行是導致您的問題的原因,問題是“在 null 上呼叫了方法 '[]'”。意思是你['something']在一個空變數(一個沒有值的變數)后面加了一個(如果你想了解什么是空更好,我寫了一篇關于空安全的文章,開頭部分專門講了什么null意思)。
很明顯,getTypeTemps沒有正確地為TTdata. 從它讀取時會導致錯誤。為什么是這樣?
原因很簡單。getTypeTemps是一種異步方法,這意味著它會在 Flutter 有空閑時間時執行,通常是在第一次運行 build 之后。
這意味著您的代碼按以下順序執行:
initState -> 構建 -> getTypeTemps。
TTdata因此,如果仍然為空,您應該采取某種安全措施。以下是您可以如何執行此操作的示例:
Widget build(BuildContext context) {
if (TTdata == null) {
return Text('loading...');
}
List<TypesTemps> ttlist = List<TypesTemps>.from(
TTdata["TTdata"].map((i){
return TypesTemps.fromJSON(i);
})
); //searilize typetemps json data to object model.
return Column(children: [
...
}
希望這個解釋很清楚,可以幫助您解決問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/435229.html
標籤:json 列表 扑 nosuchmethoderror 下拉按钮
上一篇:使用zip對串列元素求和
下一篇:C#基于元素型別過濾的物件樹
