【问题标题】:The method 'addItem' was called on null在 null 上调用了方法“addItem”
【发布时间】:2020-07-31 09:09:28
【问题描述】:

我对这种情况有意见。你能帮助我吗 ?我正在接收此错误消息。

发生异常。

NoSuchMethodError (NoSuchMethodError: 方法 'addItem' 在 null 上被调用。 接收方:空 尝试调用:addItem("{\"name\":\"example\",\"isCompleted\":false,\"isArchived\":false}"))

我在这里使用 addItem;

floatingActionButton: FloatingActionButton(
          backgroundColor: Color(0xff655c56),
          onPressed: () async {
            String itemName = await showDialog(
                context: context,
                builder: (BuildContext context) => ItemDialog());

            if (itemName.isNotEmpty) {
              var item =
                  Item(name: itemName, isCompleted: false, isArchived: false);
              _itemService.addItem(item.toJson());

              setState(() {});
            }
          },

我在这里定义了addItem;

Future<List<Item>> fetchItems() async {
    final response = await http.get(_serviceUrl);

    if (response.statusCode == 200) {
      Iterable items = json.decode(response.body);

      return items.map((item) => Item.fromJson(item)).toList();
    } else {
      throw Exception('something went wrong');
    }
  }
  Future<Item> addItem(String itemJson) async{
    final response = await http.post(_serviceUrl, headers: {
      'content-type':'application/json'
    },body: itemJson);

    if(response.statusCode==201){
      Map item= json.decode(response.body);

      return Item.fromJson(item);
    }
    else {
      throw Exception('something went wrong');
    }
  }
}

帮助! 顺便更新一下

【问题讨论】:

  • 请发布您的完整代码

标签: list flutter mobile methods


【解决方案1】:

您似乎尝试在未分配给任何东西的_itemService 上调用addItem 方法。但要获得更明确的答案,请分享与此问题相关的所有代码。

【讨论】:

    猜你喜欢
    • 2020-01-17
    • 2020-02-21
    • 2020-08-29
    • 2021-02-11
    • 2021-01-19
    • 2019-09-12
    • 2020-10-11
    • 2020-11-06
    相关资源
    最近更新 更多