这些是我到目前为止使用过的代码。
import 'dart:math';
import 'package:animated_text_kit/animated_text_kit.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_ui_firestore/firebase_ui_firestore.dart';
import 'package:flutter/material.dart';
import 'package:multiyenyewe/screen/productDetailsScreen.dart';
import 'package:multiyenyewe/screen/searchServices.dart';
import 'package:shimmer_image/shimmer_image.dart';
import '../../firebaseService.dart';
import '../../model/productModel.dart';
import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;
class DataSnapShot extends StatefulWidget {
final bool? showPants;
final FirestoreQueryBuilderSnapshot snapshot;
const DataSnapShot({
super.key,
required this.snapshot,
this.showPants
});
@override
State<DataSnapShot> createState() => _DataSnapShotState();
}
class _DataSnapShotState extends State<DataSnapShot>
with SingleTickerProviderStateMixin {
FirebaseService myService = FirebaseService();
firebase_storage.FirebaseStorage myStorage =
firebase_storage.FirebaseStorage.instance;
SearchServices search = SearchServices();
static List<ProductModel> dataList = [];
late AnimationController myController;
Animation? flipAnimation;
bool isLoading = false;
@override
void initState() {
if (mounted) {
getSearchProduct();
}
super.initState();
}
//todo GetList
getSearchProduct() async{
dataList.clear();
await FirebaseFirestore.instance.collection('products').get().then((QuerySnapshot querySnapshot) {
for (var myDocs in querySnapshot.docs) {
setState(() {
dataList.add(ProductModel(
snapshotDoc: myDocs,
productName: myDocs['productName'],
brand: myDocs['brand'],
category: myDocs['category'],
subCategoryName: myDocs['subCategoryName'],
salesPrice: myDocs['salesPrice'],
regularPrice: myDocs['regularPrice'],
priceForServices: myDocs['priceForServices'],
productDescription: myDocs['productDescription'],
location: myDocs['location'],
));
});
}
});
}
//todo product Normal Product List
@override
Widget build(BuildContext context) {
//todo Show Normal Product List Published And Unpublished
//todo Show Normal Product List Published And Unpublished
return SafeArea(
child: Container(
height: 800,
color: Colors.white ,
child: Column(
children: [
//todo searching
ClipRRect(
borderRadius: const BorderRadius.only(
bottomLeft: Radius.circular(15),
bottomRight: Radius.circular(15),
),
child: Container(
decoration: const BoxDecoration(
border: Border.fromBorderSide(BorderSide.none),
),
height: 55,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: SizedBox(
//color: Colors.blue,
height: 55,
child: TextField(
onTap: () {
search.mySearch(
context: context,
productList: dataList,
suggestionList: suggestionList());
},
readOnly: true,
decoration: InputDecoration(
filled: true,
hintText: "Search Products",
fillColor: Colors.white,
helperStyle: const TextStyle(color: Colors.black),
prefixIcon: const Icon(Icons.search, color: Colors.green,),
labelText: widget.showPants == true ? 'Find Underwear & Many More' : 'Find Cars, Mobiles & Many More',
labelStyle: const TextStyle(
color: Colors.deepOrange,
fontSize: 15,
),
contentPadding:
const EdgeInsets.only(left: 10, right: 10),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(6),
),
),
),
),
),
),
),
]),
),
),
],
),
),
);
}
}
SearchPage Class.
import 'package:cached_network_image/cached_network_image.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:search_page/search_page.dart';
import '../model/productModel.dart';
class ProductData {
ProductData({
this.hook,
this.lined,
this.opacity,
this.panel,
this.manualStart,
this.digitalStart,
this.automaticChangeOver,
this.primePower,
this.phase,
this.standByPower,
this.includedBattery,
this.memoryCapacity,
this.backLight,
this.mouse,
this.touchPad,
this.lightning,
this.microUSB,
this.usbA,
this.typeC,
this.ledLight,
this.portable,
this.backwardCompatible,
this.dataRecoveryService,
this.hardwareEncryption,
this.cameraFocus,
this.internalFlash,
this.tilTable,
this.lensIncluded,
this.dustProof,
this.controllerType,
this.numberOfBlades,
this.length,
this.computerSetup,
this.snapshotDoc,
this.repairsHardwareSoftware,
this.softwareUpgrades,
this.wirelessSetup,
this.wallMountingFlatTVs,
this.flatScreenTvRepair,
this.cameraSensorCleaning,
this.installingSoundbars,
this.iPhoneSmartPhoneRepair,
this.speakerAndStereoRepair,
this.cloudServices,
this.backupDisasterRecovery,
this.networkSecurity,
this.cctvCameraInstallation,
this.printServices,
this.antivirusInstallation,
this.softwareInstallation,
this.computerTraining,
this.iTConsulting,
this.mobileApplicationDev,
this.desktopAppDevelopment,
this.websiteDesignDevelop,
this.serverInstallation,
this.networkInstallation,
this.ultraSound,
this.regularCheckUp,
this.dermatology,
this.eyeClinic,
this.dentalClinic,
this.pediatric,
this.earNoseThroat,
this.disabledAndPhysiotherapy,
this.accidentEmergencyServices,
this.inPatientServices,
this.outPatientServices,
this.commercialCorporateLaw,
this.bankingFinanceLaw,
this.employmentLaw,
this.landLaw,
this.energyOilGasMiningLaw,
this.wildlifeTourismLaw,
this.agricultureLaw,
this.immigrationLaw,
this.telecommunicationLaw,
this.internationalTradeLaw,
this.intellectualPropertyLaw,
this.trainingLaw,
this.sizeInches,
this.displayTechnology,
this.warrant,
this.bluetooth,
this.hdmi,
this.voltage,
this.literCapacity,
this.frostFree,
this.freezerType,
this.lock,
this.smartCompressor,
this.numberShelves,
this.multiAirFlow,
this.energyStarLevel,
this.numberDrawer,
this.interiorRight,
this.productDimension,
this.reversibleDor,
this.autoOnOf,
this.countryOrigin,
this.speakerType,
this.wirelessSubwoofer,
this.wallMountable,
this.voiceAssistantBuiltIn,
this.remoteControl,
this.surroundSoundSystem,
this.auxiliaryCable,
this.stockNumber,
this.dolbyAudio,
this.livingRoom,
this.restaurant,
this.restRoom,
this.shop,
this.hotelGuestTv,
this.toilet,
this.hotelGuestPhone,
this.bathRoom,
this.backYard,
this.kitchen,
this.garden,
this.laundry,
this.furniture,
this.bathroom,
this.bedRoom,
this.houseStore,
this.parkingArea,
this.wifi,
this.electricity,
this.airCondition,
this.solarPower,
this.internetServices,
this.waterServices,
this.cctvCamera,
this.swimmingPool,
this.gatesFences,
this.sportGround,
this.measuredArea,
this.gotPlotDeed,
this.plotNumber,
this.wiperAndBrade,
this.powerWindow,
this.oilAndFilter,
this.steeringSystem,
this.tireServices,
this.carBrake,
this.carWheel,
this.engineServices,
this.airFilter,
this.carBody,
this.batteryCarService,
this.carAirCondition,
this.outerMaterial,
this.soleMaterial,
this.outerSole,
this.fabricType,
this.washingMachine,
this.neckStyle,
this.closureType,
this.analogueDigital,
this.materialType,
this.waterProof,
this.gender,
this.callText,
this.touchScreen,
this.usbType,
this.screenSize,
this.releaseDate,
this.processor,
this.ramInstalled,
this.operatingSystem,
this.specialFeature,
this.hardDiskSize,
this.displaySize,
this.wheelDrive,
this.manufactureYear,
this.registrationYear,
this.seat,
this.steering,
this.weight,
this.mileage,
this.door,
this.transmission,
this.productId,
this.modelName,
this.engineSize,
this.fuelType,
this.type,
this.approved,
this.category,
this.mainCategory,
this.imageUrls,
this.productDescription,
this.productName,
this.regularPrice,
this.salesPrice,
this.location,
this.brand,
this.unit,
this.size,
this.priceForServices,
this.otherDetails,
this.manageInventory,
this.sizeList,
this.isChargeShipping,
this.shippingCharge,
this.seller,
this.subCategoryName,
this.scheduleDate,
this.color,
this.phoneMemory,
this.productState,
this.selfieCameraPixels,
this.mainCameraPixels,
this.networkTechnology,
this.fuelTankCapacity,
this.monthlyRent,
this.diskType,
this.dishInstallation,
this.hangingSpace,
this.sofaType,
this.roomTypes,
this.bedSideTable,
this.fanType,
this.usageType,
this.zoomType,
this.ethernet,
this.boneConduction,
this.sweatProof,
this.mediaControl,
this.batteryLife,
this.wearingTypeFormFactor,
this.waterPumpInches,
this.noiseLevel,
});
final String? hook;
final String? lined;
final String? opacity;
final String? panel;
final String? noiseLevel;
final String? manualStart;
final String? digitalStart;
final String? automaticChangeOver;
final String? primePower;
final String? phase;
final String? standByPower;
final String? includedBattery;
final String? backLight;
final String? mouse;
final String? touchPad;
final String? lightning;
final String? microUSB;
final String? usbA;
final String? typeC;
final String? ledLight;
final String? portable;
final String? backwardCompatible;
final String? dataRecoveryService;
final String? hardwareEncryption;
final String? wearingTypeFormFactor;
final String? boneConduction;
final String? mediaControl;
final String? sweatProof;
final String? batteryLife;
final String? ethernet;
final String? zoomType;
final String? cameraFocus;
final String? internalFlash;
final String? tilTable;
final String? lensIncluded;
final String? dustProof;
final String? fanType;
final String? usageType;
final String? controllerType;
final String? numberOfBlades;
final String? length;
final DocumentSnapshot? snapshotDoc;
final String? sofaType;
final String? bedSideTable;
final String? roomTypes;
//todo Bellow Medical
final String? regularCheckUp;
final String? dermatology;
final String? eyeClinic;
final String? selfieCameraPixels;
final String? dentalClinic;
final String? pediatric;
final String? earNoseThroat;
final String? disabledAndPhysiotherapy;
final String? accidentEmergencyServices;
final String? inPatientServices;
final String? outPatientServices;
final String? displayTechnology;
final String? ultraSound;
final String? hangingSpace;
//todo above Medical
final String? commercialCorporateLaw;
final String? bankingFinanceLaw;
final String? employmentLaw;
final String? landLaw;
final String? energyOilGasMiningLaw;
final String? wildlifeTourismLaw;
final String? agricultureLaw;
final String? immigrationLaw;
final String? telecommunicationLaw;
final String? internationalTradeLaw;
final String? intellectualPropertyLaw;
final String? trainingLaw;
final String? livingRoom;
final String? restaurant;
final String? restRoom;
final String? shop;
final String? hotelGuestTv;
final String? toilet;
final String? hotelGuestPhone;
final String? bathRoom;
final int? monthlyRent;
final String? diskType;
final String? electricity;
final String? solarPower;
final String? airCondition;
final String? internetServices;
final String? waterServices;
final String? cctvCamera;
final String? swimmingPool;
final String? gatesFences;
final String? sportGround;
final String? networkTechnology;
final String? usbType;
final String? powerWindow;
final String? fuelTankCapacity;
final String? touchScreen;
final String? mainCameraPixels;
final String? screenSize;
final String? releaseDate;
final String? color;
final String? backYard;
final String? kitchen;
final String? garden;
final String? laundry;
final String? processor;
final String? category;
final bool? approved;
final String? mainCategory;
final List? imageUrls;
final String? productDescription;
final String? subCategoryName;
final String? productName;
final dynamic regularPrice;
final dynamic salesPrice;
final String? location;
final String? engineSize;
final String? brand;
final String? fabricType;
final String? washingMachine;
final String? neckStyle;
final String? closureType;
final String? unit;
final String? size;
final String? type;
final String? otherDetails;
final Timestamp? scheduleDate;
final String? productState;
final bool? manageInventory;
final String? productId;
final String? fuelType;
final List? sizeList;
final bool? isChargeShipping;
final int? shippingCharge;
final String? priceForServices;
final Map? seller;
final String? wheelDrive;
final String? manufactureYear;
final String? registrationYear;
final String? seat;
final String? ramInstalled;
final String? operatingSystem;
final String? specialFeature;
final String? hardDiskSize;
final String? displaySize;
final String? steering;
final String? weight;
final String? mileage;
final String? door;
final String? transmission;
final String? phoneMemory;
final String? memoryCapacity;
final String? analogueDigital;
final String? callText;
final String? materialType;
final String? gender;
final String? waterProof;
final String? outerMaterial;
final String? soleMaterial;
final String? outerSole;
final String? wiperAndBrade;
final String? oilAndFilter;
final String? steeringSystem;
final String? tireServices;
final String? carBrake;
final String? carWheel;
final String? engineServices;
final String? airFilter;
final String? carBody;
final String? batteryCarService;
final String? carAirCondition;
final String? measuredArea;
final String? gotPlotDeed;
final String? plotNumber;
final String? furniture;
final String? bathroom;
final String? bedRoom;
final String? houseStore;
final String? parkingArea;
final String? wifi;
final String? warrant;
final String? bluetooth;
final String? hdmi;
final String? voltage;
final String? literCapacity;
final String? frostFree;
final String? freezerType;
final String? lock;
final String? smartCompressor;
final String? numberShelves;
final String? multiAirFlow;
final String? energyStarLevel;
final String? numberDrawer;
final String? interiorRight;
final String? productDimension;
final String? reversibleDor;
final String? autoOnOf;
final String? countryOrigin;
final String? speakerType;
final String? wirelessSubwoofer;
final String? wallMountable;
final String? voiceAssistantBuiltIn;
final String? remoteControl;
final String? surroundSoundSystem;
final String? auxiliaryCable;
final String? stockNumber;
final String? dolbyAudio;
final String? sizeInches;
//todo electronic computer Services
final String? modelName;
final String? computerSetup;
final String? repairsHardwareSoftware;
final String? softwareUpgrades;
final String? wirelessSetup;
final String? wallMountingFlatTVs;
final String? flatScreenTvRepair;
final String? cameraSensorCleaning;
final String? installingSoundbars;
final String? iPhoneSmartPhoneRepair;
final String? speakerAndStereoRepair;
final String? cloudServices;
final String? backupDisasterRecovery;
final String? networkSecurity;
final String? cctvCameraInstallation;
final String? printServices;
final String? antivirusInstallation;
final String? softwareInstallation;
final String? computerTraining;
final String? iTConsulting;
final String? mobileApplicationDev;
final String? desktopAppDevelopment;
final String? websiteDesignDevelop;
final String? serverInstallation;
final String? networkInstallation;
final String? dishInstallation;
final String? waterPumpInches;
//todo above Medical
}
class SearchServices {
mySearch({context, productList, suggestionList}) {
showSearch(
context: context,
delegate: SearchPage<ProductModel>(
onQueryUpdate: (s) => const Center(child: CircularProgressIndicator(),),
items: productList,
barTheme: ThemeData(),
searchLabel: 'Search Products',
suggestion: suggestionList,
failure: const Center(child: Text('No Product / Services Found :(')),
filter: (product) => [
product.productName,
product.category,
product.brand,
product.subCategoryName,
],
builder: (product) =>
ListTile(title: Text(product.productName!),)
));
}
}
您的
SearchDelegate
课程似乎比需要的更复杂。尝试一个更简单的搜索功能,如下所示:
Future<List<ProductModel>> searchProducts(String query) async {
final firestore = FirebaseFirestore.instance;
final results = await firestore.collection('products')
.where('keywords', arrayContains: query.toLowerCase())
.get();
return results.docs.map((doc) => ProductModel.fromFirestore(doc)).toList();
}
ProductModel 看起来像这样:
class ProductModel {
final String? productName;
final String? category;
final String? brand;
final String? subCategoryName;
ProductModel({this.productName, this.category, this.brand, this.subCategoryName});
factory ProductModel.fromFirestore(DocumentSnapshot doc) {
Map data = doc.data() as Map<String, dynamic>;
return ProductModel(
productName: data['productName'] ?? '',
category: data['category'] ?? '',
brand: data['brand'] ?? '',
subCategoryName: data['subCategoryName'] ?? '',
);
}
}