Flutter-方法“ map”在null上被调用
尝试使用对象模型从我的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,
);
}
}
如何解决这个问题?
回答:
传递一个空容器中,同时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() ?? [],
以上是 Flutter-方法“ map”在null上被调用 的全部内容, 来源链接: utcz.com/qa/426968.html