如果我在列出我的列表中搜索的东西,屏幕会空白

发布于 2025-02-10 06:09:06 字数 2979 浏览 3 评论 0原文

我在另一个目录中创建了一个列表,该目录是JSON数据的列表,并且在屏幕上显示了它,还添加了一个用作搜索栏的文本字段。如果我搜索列表中的字母(或字母的组合),但是当我从列表中搜索某些内容时,整个页面除外时,Appbar除外时,它可以正常工作。 这是我的代码:

import 'package:flutter/material.dart';
import 'dart:convert';

import 'package:flutter/services.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      // Hide the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

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

class _HomePageState extends State<HomePage> {
  List _items = [];
  List _itemsForDisplay = [];

  // Fetch content from the json file
  Future<void> readJson() async {
    final String response = await rootBundle.loadString('assets/Symptoms.json');
    final data = await json.decode(response);
    setState(() {
      _items = data["Symptoms"];
      _itemsForDisplay = _items;
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    readJson();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text(
          'Diagnose',
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(25),
        child: Column(
          children: [
            // Display the data loaded from sample.json

            Expanded(
              child: ListView.builder(
                itemBuilder: (context, index) {
                  return index == 0 ? _searchBar() : _ListItem(index);
                },
                itemCount: _itemsForDisplay.length,
              ),
            )
          ],
        ),
      ),
    );
  }

  _searchBar() {
    return Padding(
      padding: const EdgeInsets.all(8),
      child: TextField(
        decoration: InputDecoration(hintText: 'Search'),
        onChanged: (text) {
          text = text.toLowerCase();
          setState(() {
            _itemsForDisplay = _items.where((item) {
              var itemTitle = item.toLowerCase();
              return itemTitle.contains(text);
            }).toList();
          });
        },
      ),
    );
  }

  _ListItem(index) {
    return Card(
      margin: const EdgeInsets.all(10),
      child: ListTile(
        leading: Text(_itemsForDisplay[index]),
      ),
    );
  }
}

这是一张图片,然后搜索我列表的实体的东西

,当我搜索“”。或我列表中没有的任何东西:

I have created a list in another directory which is a list of JSON data and I have showed it on screen and also added a TextField which works as a search bar. it works fine if I search for a letter(or combination of letters) that is inside my list but when I search for something out of list the whole page goes blank except for the Appbar.
here's my code:

import 'package:flutter/material.dart';
import 'dart:convert';

import 'package:flutter/services.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      // Hide the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

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

class _HomePageState extends State<HomePage> {
  List _items = [];
  List _itemsForDisplay = [];

  // Fetch content from the json file
  Future<void> readJson() async {
    final String response = await rootBundle.loadString('assets/Symptoms.json');
    final data = await json.decode(response);
    setState(() {
      _items = data["Symptoms"];
      _itemsForDisplay = _items;
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    readJson();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text(
          'Diagnose',
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(25),
        child: Column(
          children: [
            // Display the data loaded from sample.json

            Expanded(
              child: ListView.builder(
                itemBuilder: (context, index) {
                  return index == 0 ? _searchBar() : _ListItem(index);
                },
                itemCount: _itemsForDisplay.length,
              ),
            )
          ],
        ),
      ),
    );
  }

  _searchBar() {
    return Padding(
      padding: const EdgeInsets.all(8),
      child: TextField(
        decoration: InputDecoration(hintText: 'Search'),
        onChanged: (text) {
          text = text.toLowerCase();
          setState(() {
            _itemsForDisplay = _items.where((item) {
              var itemTitle = item.toLowerCase();
              return itemTitle.contains(text);
            }).toList();
          });
        },
      ),
    );
  }

  _ListItem(index) {
    return Card(
      margin: const EdgeInsets.all(10),
      child: ListTile(
        leading: Text(_itemsForDisplay[index]),
      ),
    );
  }
}

Here's a picture before for searching for something that is an entity of my list
enter image description here

and this happens when I search for "." or anything that is not in my list:
enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

醉南桥 2025-02-17 06:09:06

在您的项目中,构建器仅返回_listItem(index),然后放置_Searchbar在扩展的外部。在当前代码中,您从列表跳过了第一个元素,而是显示搜索栏,这是错误的。这就是为什么当列表为0时,您什么都看不到。因为建造者没有被执行。

因此,您的构建方法应该看起来像这样:

 @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text(
          'Diagnose',
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(25),
        child: Column(
          children: [
            // Display the data loaded from sample.json
            _searchBar(),
            Expanded(
              child: ListView.builder(
                itemBuilder: (context, index) {
                  return _ListItem(index);
                },
                itemCount: _itemsForDisplay.length,
              ),
            )
          ],
        ),
      ),
    );
  }

In your item builder return only _ListItem(index) and put _searchBar outside of Expanded. In current code, you are skipping first element from list and showing search bar instead, which is wrong. That's why when length of list is 0 you don't see anything. Because builder doesn't get executed.

So, your built method should look like this:

 @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text(
          'Diagnose',
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(25),
        child: Column(
          children: [
            // Display the data loaded from sample.json
            _searchBar(),
            Expanded(
              child: ListView.builder(
                itemBuilder: (context, index) {
                  return _ListItem(index);
                },
                itemCount: _itemsForDisplay.length,
              ),
            )
          ],
        ),
      ),
    );
  }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文