【发布时间】:2021-09-26 08:20:28
【问题描述】:
我对 Flutter 很陌生,我正在尝试通过他们的 ID 获取存储在地图中的数据。
我曾尝试使用 map() 函数,但这并没有任何用处。
我得到的错误是The return type 'bool' isn't a 'MapEntry<_, _>', as required by the closure's context.
我什至尝试将地图转换为列表,但这也不起作用。
这是我的代码:
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
class Products {
final String id;
final String title;
final String description;
final double price;
final String imageUrl;
Products({
required this.id,
required this.title,
required this.description,
required this.price,
required this.imageUrl
});
}
class ProductItems with ChangeNotifier {
Map<String, Products> _items = {};
Map<String, Products> get items {
return {..._items};
}
void addItems(Products products) {
_items.putIfAbsent(products.id, () => Products(
id: products.id,
title: products.title,
description: products.description,
price: products.price,
imageUrl: products.imageUrl
));
notifyListeners();
}
Map<String, Products> findById(String productId) {
return items.map((key, value) => value.id == productId).toList(); //this is where the error is
}
}
想法是将下面代码 sn-p 中的 id 传递到“/edit-view-data”屏幕,然后在那里调用 findById 方法。下一个屏幕上的预期输出应在其 Appbar 上显示标题,例如存储在地图中的 Red Shirt 以及类似的所有其他属性以及其他小部件中的标题。 我认为这样做的唯一方法是通过产品的 ID 过滤地图。
trailing: Container(
width: 150,
child: Row(
children: [
IconButton(
onPressed: () {
Navigator.of(context).pushNamed(
'/edit-view-data',
arguments: id
);
},
icon: Icon(Icons.edit, color: Colors.blue)
)
【问题讨论】:
-
嘿coolhack7,我们又见面了,你能添加你的预期输出吗?
-
嘿!!!!没错
-
只是确认一下,你试图根据 id 返回一个 Product 对象吗?
-
是的。没错
-
抱歉,我花了一些时间来解决空安全问题