为什么我得到类型为“'List<dynamic>'的值无法从函数'items'返回,因为它的返回类型为'List<Item>'”

问题描述 投票:0回答:1

当我尝试运行此代码时,它向我抛出错误。我知道我的返回类型不匹配,但我不知道应该做什么来纠正它。 我尝试将返回类型转换为字符串,但问题仍然存在。如果我将返回类型设置为可为空,那么问题也不会消失。我对这门语言很陌生,仍在尝试理解,所以请帮助。 :)

这是我的代码-

import 'package:flutter_catalog/models/catalog.dart';

class CartModel {
  static final cartModel = CartModel._internal();

  CartModel._internal();

  factory CartModel() => cartModel;

  //Catalog field
  CatalogModel? _catalog;

  //Collection of IDs - store IDs of each item
  final List<int> _itemIds = [];

  //Get Catalog
  CatalogModel? get catalog => _catalog;

  set Catalog(CatalogModel newCatalog) {
    _catalog = newCatalog;
  }

  //Get item in the cart
  List<Item> get items => _itemIds.map((id) => _catalog?.getById(id)).toList();

  //Get total price
  num get totalPrice =>
      items.fold(0, (total, current) => current.price! + total);

  //Add Item
  void add(Item item) {
    _itemIds.add(item.id!.toInt());
  }

  //Remove Item
  void remove(Item item) {
    _itemIds.remove(item.id);
  }
}

这里是Item类的参考-

class CatalogModel {
  static final catModel = CatalogModel._internal();

  CatalogModel._internal();

  factory CatalogModel() => catModel;

  static List<Item> items = [];

  //Get item by ID
  getById(int id) =>
      items.firstWhere((element) => element.id == id, orElse: null);

  //Get Item by Position
  Item getByPosition(int pos) => items[pos];
}

class Item {
  final int? id;
  final String? name;
  final String? desc;
  final num? price;
  final String? color;
  final String? image;

  Item({this.id, this.name, this.desc, this.price, this.color, this.image});

  factory Item.fromMap(Map<String, dynamic> map) {
    return Item(
      id: map["id"],
      name: map["name"],
      desc: map["desc"],
      price: map["price"],
      color: map["color"],
      image: map["image"],
    );
  }
}

发生异常。 NoSuchMethodError(NoSuchMethodError:“String”类没有实例 getter“text”。 接收者:“iPhone 12 Pro” 尝试致电:短信) enter image description here

谁能指出我哪里出错了?

flutter list dart dynamic
1个回答
0
投票

第一个问题是

CatalogModel.getById
没有声明的返回类型,因此推断它是动态的。声明一个返回类型来解决这个问题:

//Get item by ID
Item? getById(int id) =>
    items.firstWhereOrNull((element) => element.id == id);

那么你就会遇到问题,

CatalogModel.getById
返回一个
Item?
,你需要构建一个
Item
列表。处理此问题的正确方法取决于您的应用程序:是否预期某些 id 不会解析为项目,因此可以忽略空结果,或者这是意外的情况,因此应该抛出错误?对我来说,装有物品的购物车听起来更像是第二种情况,所以这里是它的代码:

//Get item in the cart
List<Item> get items => _itemIds.map((id) => _catalog!.getById(id)!).toList();

之后应该可以编译了。始终为您的函数提供返回类型。

© www.soinside.com 2019 - 2024. All rights reserved.