【问题标题】:Extract data from map by ID按 ID 从地图中提取数据
【发布时间】: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 对象吗?
  • 是的。没错
  • 抱歉,我花了一些时间来解决空安全问题

标签: flutter dart


【解决方案1】:

好吧,既然您尝试返回 Products 类,只需将您的 findbyid 函数更改为:

Products? findById(String productId) {
    return _items[productId]; //this is the fix 
  }  

它将返回一个 Products 类,您可以直接访问成员,例如:

Products? p = productItems.findById("123")!;  
print(p.title);

【讨论】:

  • 如果我理解错了,请告诉我,我会更新答案
  • 工作得很好。再一次感谢你。虽然,没有任何方法可以遍历地图并像在列表中那样通过存储的数据的 ID 对其进行过滤?
  • 对不起,但我不明白你的意思是遍历地图并按 id 过滤,是不是你想遍历所有地图元素,然后返回 id 是给定ID?
猜你喜欢
  • 2019-08-04
  • 2021-09-26
  • 2017-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多