尝试使用对象模型将我的API JSON中的元素添加到DropdownMenuItem
这是错误:
The method 'map' was called on null.
Receiver: null
Tried calling: map<DropdownMenuItem<Provinces>>(Closure: (Provinces) => DropdownMenuItem<Provinces>)
这是我的飞镖代码:
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:sj/utils/constants.dart';
import 'package:http/http.dart' as http;
import 'package:sj/models/master/provinces.dart';
class IdCardFormPage extends StatefulWidget {
@override
_IdCardFormPageState createState() => new _IdCardFormPageState();
}
class _IdCardFormPageState extends State<IdCardFormPage> {
List<Provinces> listProvinces;
Provinces _selectedProvince;
Future<List<Provinces>> getProvinceList() async {
//final response = await http.get("${APIConstants.API_BASE_URL}api/masters/provincesList.php");
final response = await http.get("url");
listProvinces = parseProvinces(response.body);
return parseProvinces(response.body);
}
List<Provinces> parseProvinces(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Provinces>((json) => Provinces.fromJson(json)).toList();
}
@override
void initState() {
getProvinceList();
super.initState();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(title: new Text("MASUK"),),
body: _provinceContainer(),
);
}
Widget _provinceContainer(){
return new Container(
child: new InputDecorator(
decoration: InputDecoration(
suffixIcon: new Icon(
Icons.account_balance,
color: Colors.pink,
),
labelText: LoanEntryField.PD_BANKNAME, labelStyle: TextStyle(fontSize: 16.0)
),
isEmpty: _selectedProvince == null,
child: new DropdownButtonHideUnderline(
child: new DropdownButton<Provinces>(
value: _selectedProvince,
isDense: true,
onChanged: (Provinces newValue) {
setState(() {
_selectedProvince = newValue;
});
},
items: listProvinces.map((Provinces value) {
return new DropdownMenuItem<Provinces>(
value: value,
child: new Text(value.name, style: new TextStyle(fontSize: 16.0),),
);
}).toList(),
),
),
),
margin: EdgeInsets.only(bottom: 10.0));
}
}
class Provinces{
String id;
String name;
Provinces({this.id, this.name});
factory Provinces.fromJson(Map<String, dynamic> json) {
return Provinces(
id: json['id'] as String,
name: json['name'] as String,
);
}
}
如何解决此问题?
答案 0 :(得分:1)
在listProvices
为null
时传递一个空容器:
items: listProvices?.map((Provinces value) {
return new DropdownMenuItem<Provinces>(
value: value,
child: new Text(value.name, style: new TextStyle(fontSize: 16.0),),
);
})?.toList() ?? [],
答案 1 :(得分:0)
我有一个类似的问题,可以通过将其包装在检查列表中是否包含超过0个项目的条件中来解决。
答案 2 :(得分:0)
尝试将没有分配值列表传递给DorpdownMenu小部件的items属性时遇到了相同的问题。
错误消息The method 'map' was called on null
。表示您已将索引[ ]
调用为null。
因此,在使用List
之前,请为其指定一个值List或Initialize the List。
我确实初始化了列表,并按照以下代码对其进行了修复
List<Provinces> listProvinces = [];
在容器编译器未编译时它仍然可以工作
答案 3 :(得分:-3)
检查所有拼写错误,有时可能会在出现拼写错误时发生。