草庐IT

dart - Flutter - 在 null 上调用了方法 'map'

coder 2023-07-22 原文

我在尝试使用对象模型从我的 api JSON 添加元素到 DropdownMenuItem

时收到以下错误

这里是错误:

The method 'map' was called on null.
Receiver: null
Tried calling: map<DropdownMenuItem<Provinces>>(Closure: (Provinces) => DropdownMenuItem<Provinces>)

这是我的 Dart 代码:

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

}

如何解决这个问题?

最佳答案

listProvicesnull 时传递一个空容器:

items: listProvices?.map((Provinces value) {
            return new DropdownMenuItem<Provinces>(
              value: value,
              child: new Text(value.name, style: new TextStyle(fontSize: 16.0),),
            );
          })?.toList() ?? [],

关于dart - Flutter - 在 null 上调用了方法 'map',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51036758/

有关dart - Flutter - 在 null 上调用了方法 'map'的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  5. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  6. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  7. Ruby 方法() 方法 - 2

    我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby​​-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco

  8. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  9. ruby - Highline 询问方法不会使用同一行 - 2

    设置:狂欢ruby1.9.2高线(1.6.13)描述:我已经相当习惯在其他一些项目中使用highline,但已经有几个月没有使用它了。现在,在Ruby1.9.2上全新安装时,它似乎不允许在同一行回答提示。所以以前我会看到类似的东西:require"highline/import"ask"Whatisyourfavoritecolor?"并得到:Whatisyourfavoritecolor?|现在我看到类似的东西:Whatisyourfavoritecolor?|竖线(|)符号是我的终端光标。知道为什么会发生这种变化吗? 最佳答案

  10. ruby - 在 jRuby 中使用 'fork' 生成进程的替代方案? - 2

    在MRIRuby中我可以这样做:deftransferinternal_server=self.init_serverpid=forkdointernal_server.runend#Maketheserverprocessrunindependently.Process.detach(pid)internal_client=self.init_client#Dootherstuffwithconnectingtointernal_server...internal_client.post('somedata')ensure#KillserverProcess.kill('KILL',

随机推荐