You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中ListView.builder搜索功能实现求助

Fixing Search for Your Disease ListView in Flutter

Hey there! Let's fix your search functionality step by step. I can see the issue right away—your current code is working with dummy Item $i data instead of your actual Disease list, and your ListView isn't using the filtered results at all. Let's get this sorted.

What's Wrong With the Current Code?

  • You're maintaining two separate datasets: your real Disease list (disease = Data.disease) and dummy string lists (duplicateItems, items)
  • Your filterSearchResults method only filters the dummy strings, not your disease data
  • The ListView.builder is still rendering the full, unfiltered disease list instead of the filtered results

The Solution

We need to refactor the code to work directly with your Disease objects, not dummy strings. Here's how:

  1. Update your state variables to hold the original disease list and the filtered list (both of type List<Disease>)
  2. Adjust initState to initialize these lists with your real data
  3. Rewrite the filterSearchResults method to filter based on the title property of Disease
  4. Update the ListView to use the filtered list instead of the original one

Modified Full Code for MyHomePage

import 'package:flutter/material.dart';
import 'package:yellow_book/utils/class.dart';
import 'package:yellow_book/utils/data.dart';

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title = ''}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  // Original full list of diseases
  List<Disease> originalDiseases = Data.disease;
  // Filtered list that will be displayed
  List<Disease> filteredDiseases = [];
  TextEditingController editingController = TextEditingController();

  @override
  void initState() {
    // Initialize filtered list with all diseases on app start
    filteredDiseases.addAll(originalDiseases);
    super.initState();
  }

  void filterSearchResults(String query) {
    List<Disease> dummyFilteredList = [];
    
    if (query.isNotEmpty) {
      // Iterate through original list and check if title contains the query (case-insensitive)
      dummyFilteredList = originalDiseases.where((disease) {
        return disease.title.toLowerCase().contains(query.toLowerCase());
      }).toList();
      
      setState(() {
        filteredDiseases.clear();
        filteredDiseases.addAll(dummyFilteredList);
      });
    } else {
      // If query is empty, reset to full list
      setState(() {
        filteredDiseases.clear();
        filteredDiseases.addAll(originalDiseases);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(
        children: [
          TextField(
            onChanged: (value) {
              filterSearchResults(value);
            },
            controller: editingController,
            decoration: InputDecoration(
              hintText: "Search Diseases",
              prefixIcon: Icon(Icons.search),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.all(
                  Radius.circular(0.0),
                ),
              ),
            ),
          ),
          Expanded(
            child: ListView.builder(
              // Use filtered list's length instead of original
              itemCount: filteredDiseases.length,
              itemBuilder: (context, index) {
                return Card(
                  child: ListTile(
                    onTap: () {
                      // You can add navigation or detail view here later
                    },
                    // Display title from filtered list
                    title: Text(filteredDiseases[index].title),
                  ),
                );
              },
            ),
          )
        ],
      ),
    );
  }
}

Key Changes Explained

  • State Variables: Replaced dummy string lists with originalDiseases (full data) and filteredDiseases (dynamic results)
  • Case Insensitivity: Added .toLowerCase() to both the disease title and search query so searches work regardless of capitalization (e.g., searching "dengue" or "DENGUE" will find the same result)
  • ListView Binding: Now the ListView uses filteredDiseases for both itemCount and the data displayed in ListTile
  • Cleaner Filter Logic: Used where() method instead of a forEach loop for more concise and readable filtering

This should give you a fully functional search feature that works with your actual disease data!

内容的提问来源于stack exchange,提问作者wilfredmd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 14:17:45