我想在<dynamic>飞镖中搜索列表



我有一个产品列表,列表如下:

List<dynamic>products = [
{
"id": 3,
"name": "Apple MacBook Air 13.3-Inch 10th Gen Core i3-1.1GHz, 8GB RAM, 256GB SSD (MWTJ2) Space Gray 2020",
"price": 126000,
"descriptions": "ProcessortIntel Core i3-1000NG4 Processor (4M Cache, 1.10 GHz up to 3.20 GHz)rnrnMemoryt        8GB 3733MHz LPDDR4X onboard RAMrnrnStoraget        256GB SSDrnGraphicstIntel Iris Plus Graphics; **Support for Thunderbolt 3–enabled external graphics processors (eGPUs)rnrnDisplayt        13.3-inch (diagonal) Retina LED-backlit display with IPS technology; 2560-by-1600 native resolution at 227 pixels per inch with support for millions of colorsrnrnAdaptert        30W USB-C Power Adapter; USB-C power portrnrnBatterytUp to 10 hours battery back (Video & web browsing up to 05 hours depending on resolution) Built-in 49.9 watt-hours lithium-polymer batteryrnrnOperating SystemtmacOSrnrnNetworkingt                802.11ac Wi-Fi wireless networking; IEEE 802.11a/b/g/n compatiblernrnTouchpadt                Multi-Touch gesturesrnrnKeyboardtBacklit Keyboard - US English Retina is equipped with: 78 keys (ANSI specification) or 79 keys (ISO specification), including 12 function keys and 4 direction keys arranged in an "inverted T" shape. Ambient light sensor Force touchpad brings precise cursors Control and pressure-sensing functions, support forceful long-press, acceleration function, pressure-sensitive drawing, and multi-touch gesturesrnrnBluetoothtBluetooth 5.0 wireless technologyrnrnAudiot        Stereo speakers; Wide stereo sound; Support for Dolby Atmos playback; Three-mic array with directional beamforming; 3.5 mm headphone jackrnrnOptical Drive  NonernrnSoftwaretFinal Cut Pro X; Logic Pro XrnrnWebCamt720p FaceTime HD camerarnrnFingerprinttYesrnrnDisplay TouchtDisplay WithTouch ID sensorrnrnPorts & Connectorst2 x Thunderbolt 3 (Supports DisplayPort and Power Delivery); Thunderbolt (up to 40Gb / s); USB 3.1 Gen 2 (up to 10Gb / s; 1 x HDMI; 1 x VGA; 1 x 3.5 mm Headphone OutputrnrnColortSpace GrayrnrnDimensions (W x D x H)tThickness: 0.41 to 1.61 cm (0.16 to 0.63 inches); Width: 30.41 cm (11.97 inches); Depth: 21.24 cm (8.36 inches)rnrnWeightt1.29 kg (2.8 lbs)rnrnIncluded in the BoxtMacBook Air; 30W USB-C Power Adapter; USB-C Charge Cable (2 m)rnrnWarranty t01 year International Limited Warranty (Terms & Condition Apply As Per Apple)",
"image": "/images/macbook_IU3NvNF.jpg",
"created_at": "2022-08-19T17:42:13.118095Z",
"updated_at": "2022-08-19T17:42:13.118095Z",
"stock": true,
"category": 1,
"user": "mosta"
},
{
"id": 2,
"name": "MSI Modern 14 B10MW Core i3 10th Gen 14" Full HD Laptop",
"price": 50890,
"descriptions": "Processor   Intel Core i3 10110U Processor (4MB Cache, 2.1Ghz up to 4.1Ghz)rnrnDisplay        14.0" FHD (1920x1080), IPS-Level DisplayrnrnMemory       4GB 2666MHz DDR4 RAM, (Suppoorted Up to 16GB)rnrnStorage        256GB NVMe SSD (Supported Up to 1TB)rnrnGraphics      Intel UHD GraphicsrnrnOperating System     Free DosrnBattery         39.3WhrrnrnAdapter       65W adapterrnrnInput DevicesrnKeyboard    Backlight KeyboardrnrnWebCam     HD type (30fps@720p)rnCard Reader  1x Micro SDrnrnNetwork & Wireless ConnectivityrnWi-Fi            802.11 ac Wi-FirnrnBluetooth   Bluetooth v5rnrnPorts, Connectors & SlotsrnUSB (s)      2x Type-A USB2.0rnrn1x Type-C    USB3.2 Gen2rnrnHDMI        1x (4K @ 30Hz) HDMIrnrnAudio Jack Combo    1x Mic-in/Headphone-out Combo JackrnrnExtra RAM Slot   NOrnrnExtra M.2 Slot     NOrnrnPhysical SpecificationrnDimensions (W x D x H)    319 x 220.2 x 16.9 mmrnrnWeight                1.3 kgrnrnColor(s)              Carbon GrayrnrnWarrantyrnManufacturing Warranty    02 Year",
"image": "/images/msi_sCwzOcI.jpeg",
"created_at": "2022-08-19T17:41:53.358014Z",
"updated_at": "2022-08-19T17:41:53.358014Z",
"stock": true,
"category": 1,
"user": "mosta"
},
{
"id": 1,
"name": "iPhone 13 Pro Max",
"price": 169000,
"descriptions": "First ReleasetSeptember 24, 2021rnrnColorstGraphite, Gold, Silver, Sierra BluernrnNetworkt2G, 3G, 4G, 5GrnrnSIMtNano / Electronic SIMrnrnWLANt✅ dual-band, Wi-Fi hotspotrnrnBluetootht✅ v5.0, A2DP, LErnrnGPSt✅ A-GPS, GLONASS, GALILEO, BDS, QZSSrnrnRadiot✖rnrnUSBtLightning, USB 2.0rnrnOTGt✅rnrnUSB Type-Ct✖ (Proprietary reversible connector)rnrnNFCt✅rnrnStyletNotchrnrnMaterialt        Gorilla Glass front & back, stainless steel framernrnWater Resistancet✅ IP68 dust/water resistant (up to 6m for 30 mins)rnrnDimensionst160.8 x 78.1 x 7.7 mmillimetersrnrnWeightt240 gramsrnrnSizet6.7 inchesrnrnResolutiont1284 x 2778 pixels (458 ppi)rnrnTechnologytSuper Retina XDR OLED TouchscreenrnrnProtectiont✅ Scratch-resistant ceramic glass, oleophobic coatingrnrnFeaturestDolby Vision, HDR10, 1200 nits (max.), 120Hz, true-tone, wide color gamutrnrnResolutiontQuad 12+12+12 Megapixel + TOF 3D LiDAR scannerrnrnFeaturestDual Pixel PDAF, sensor-shift OIS, dual-LED flash, ultrawide, depth, telephoto, 3x optical zoom & morernrnVideo Recordingt4K (2160p), Dolby Vision HDR, ProRes, Cinematic mode, stereo sound rec.rnrnResolutiontDual 12 Megapixel + SL 3DrnrnFeaturestF/2.2, HDR, 1/3.6″, depth / biometrics sensorrnrnVideo Recordingt4K (2160p), gyro-EISrnrnType and CapacitytLithium-ion 4352 mAh (non-removable)rnrnFast Chargingt✅ 27W Fast Charging (50% in 30 minutes)rnrnUSB Power Delivery 2.0rnrnWireless Chargingt✅ Fast Wireless Charging (15W MagSafe, 7.5W Qi magnetic)rnrnOperating SystemtiOS 15rnrnChipsettApple A15 Bionic (5 nm)rnrnRAMt6 GBrnrnProcessortHexa-core, up to 3.22 GHzrnrnGPUtApple GPU (5-core graphics)",
"image": "/images/iPhone13promax_YiZ3ktK.jpg",
"created_at": "2022-08-19T17:41:27.837767Z",
"updated_at": "2022-08-19T17:41:27.837767Z",
"stock": true,
"category": 2,
"user": "mosta"
}
]

我想按产品名称在上面的列表中搜索。并且还希望一个单独的列表包含一个映射。

如果我搜索";苹果;结果应该是:

List<dynamic> searchResult = [
{
"id": 3,
"name": "Apple MacBook Air 13.3-Inch 10th Gen Core i3-1.1GHz, 8GB RAM, 256GB SSD (MWTJ2) Space Gray 2020",
"price": 126000,
"descriptions": "ProcessortIntel Core i3-1000NG4 Processor (4M Cache, 1.10 GHz up to 3.20 GHz)rnrnMemoryt        8GB 3733MHz LPDDR4X onboard RAMrnrnStoraget        256GB SSDrnGraphicstIntel Iris Plus Graphics; **Support for Thunderbolt 3–enabled external graphics processors (eGPUs)rnrnDisplayt        13.3-inch (diagonal) Retina LED-backlit display with IPS technology; 2560-by-1600 native resolution at 227 pixels per inch with support for millions of colorsrnrnAdaptert        30W USB-C Power Adapter; USB-C power portrnrnBatterytUp to 10 hours battery back (Video & web browsing up to 05 hours depending on resolution) Built-in 49.9 watt-hours lithium-polymer batteryrnrnOperating SystemtmacOSrnrnNetworkingt                802.11ac Wi-Fi wireless networking; IEEE 802.11a/b/g/n compatiblernrnTouchpadt                Multi-Touch gesturesrnrnKeyboardtBacklit Keyboard - US English Retina is equipped with: 78 keys (ANSI specification) or 79 keys (ISO specification), including 12 function keys and 4 direction keys arranged in an "inverted T" shape. Ambient light sensor Force touchpad brings precise cursors Control and pressure-sensing functions, support forceful long-press, acceleration function, pressure-sensitive drawing, and multi-touch gesturesrnrnBluetoothtBluetooth 5.0 wireless technologyrnrnAudiot        Stereo speakers; Wide stereo sound; Support for Dolby Atmos playback; Three-mic array with directional beamforming; 3.5 mm headphone jackrnrnOptical Drive  NonernrnSoftwaretFinal Cut Pro X; Logic Pro XrnrnWebCamt720p FaceTime HD camerarnrnFingerprinttYesrnrnDisplay TouchtDisplay WithTouch ID sensorrnrnPorts & Connectorst2 x Thunderbolt 3 (Supports DisplayPort and Power Delivery); Thunderbolt (up to 40Gb / s); USB 3.1 Gen 2 (up to 10Gb / s; 1 x HDMI; 1 x VGA; 1 x 3.5 mm Headphone OutputrnrnColortSpace GrayrnrnDimensions (W x D x H)tThickness: 0.41 to 1.61 cm (0.16 to 0.63 inches); Width: 30.41 cm (11.97 inches); Depth: 21.24 cm (8.36 inches)rnrnWeightt1.29 kg (2.8 lbs)rnrnIncluded in the BoxtMacBook Air; 30W USB-C Power Adapter; USB-C Charge Cable (2 m)rnrnWarranty t01 year International Limited Warranty (Terms & Condition Apply As Per Apple)",
"image": "/images/macbook_IU3NvNF.jpg",
"created_at": "2022-08-19T17:42:13.118095Z",
"updated_at": "2022-08-19T17:42:13.118095Z",
"stock": true,
"category": 1,
"user": "mosta"
}]

如何实现这一步?

import'package:collection/collection.dart';并使用firstWhereOrNull;示例:

searchArray(String searchValue){
var test =
products.firstWhereOrNull((element) => element['name'].contains(searchValue));
print(test); //print just first object whos name property contains "MSI"

}或

searchArray(String searchValue) {

var test =
products.where((element) => element['name'].toString().contains(searchValue));
if (test != null) {
for (var testItem in test) {
print(testItem); //print all maps whos contains sV
}
}

}

以下是一种方法,您可以使用它来搜索列表中的某个查询,并使用for in iterables 将结果添加到另一个列表中

void search(String query) {
List<dynamic> searchResult = [];


for (final product in products) {
if (product["name"].toLowerCase().contains(query.toLowerCase())) {
searchResult.add(product);
print(searchResult);
return;
}
}
}

此处为完整代码

或者你可以在Kendru 提到的飞镖收集中使用firstWhereOrNull

最新更新