繁体   English   中英

如何在列表视图数据中实现搜索栏从本地 json 文件中检索

[英]How to implement search bar In list view data Retrieve from local json file

你好朋友,我正在我的列表视图中检索 json 数据,我的资产文件夹中的这个 json 文件现在我想在我的 flutter 应用程序中实现搜索栏,请帮助如何解决这个问题,它在我的应用程序中非常重要的部分我有 5 flutter 应用程序因此用户通过搜索栏搜索特定单词任何专家都在这里可以帮助我

    import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:dio/dio.dart';
import 'package:hebrew/dictinary/Meaning.dart';
class Dictionary extends StatefulWidget {
  @override
  _DictionaryState createState() => _DictionaryState();
}

class _DictionaryState extends State<Dictionary> {

  List data=[];
  List searchword=[];
  Future<String>loadjsondata()async{
  var jsonText=await rootBundle.loadString('assets/hebrew.json');

setState(() {

  data=json.decode(jsonText);


});
  print(jsonText);
}

  @override
  void initState() {
    super.initState();
  setState(() {
    loadjsondata();
  });
  }

  bool issearching=false;

 void _filtwewords(value){

  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(

          title:!issearching ?Text('Hebrew Dictionary')
            : TextField(
            onChanged: (value) {
              _filtwewords(value);
    },
      style: TextStyle(color: Colors.white),
      decoration: InputDecoration(
          icon: Icon(
            Icons.search,
            color: Colors.white,
          ),
          hintText: "Search Words...",
          hintStyle: TextStyle(color: Colors.white)),
    ),

    actions:<Widget> [
      this.issearching ? IconButton(
        icon: Icon(Icons.cancel),
        onPressed: () {
          setState(() {

            this.issearching = false;
          });
        },
      )
          : IconButton(
        icon: Icon(Icons.search),
        onPressed: () {
          setState(() {
            this.issearching =true;
          });
        },
      )

],
        ),


        body:Padding(
          padding:EdgeInsets.all(5),

          child: new ListView.separated(
             separatorBuilder: (context, index) => Divider(
             ),
             itemCount:data==null ? 0 :data.length,
             itemBuilder: (BuildContext ctxt, int index) {
               return Padding(
                 padding: EdgeInsets.all(4),
                 child: Column(
                   crossAxisAlignment:CrossAxisAlignment.stretch,
                   children: [

                     SizedBox(height: 10,),
                     GestureDetector(
                       onTap: () {
                         Navigator.push (context,MaterialPageRoute(builder: (context) =>Meaning(data[index]['eng'],data[index]['hebrew'],data[index]['urdu'])));
                       },
                       child: Text(data[index]['eng'],style: TextStyle(
                           fontSize: 15
                       ),),
                     ),

                   ],

                 ),

               );
             }
              ),
        )
    );
  }
}

所以我只是使用本地 JSON 文件为搜索数据编写了代码。 首先,我创建了一个空list和该列表中的所有数据,并创建了一个列表视图。 之后创建一个TextField并检查textfield是否为空,然后显示完整数据,否则在另一个列表中添加搜索数据并在listview上显示此数据

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.teal,
      ),
      home: SelectionScreen(),
    );
  }
}

class SelectionScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _selectionScreen();
  }
}

class _selectionScreen extends State<SelectionScreen> {
  List fullData = new List();
  List searchData = new List();
  TextEditingController textEditingController = new TextEditingController();

  @override
  initState() {
    super.initState();
    getLocalJsonData();
  }

  getLocalJson() {
    return rootBundle.loadString('assets/data.json');   // Read your local Data 
  }

  Future getLocalJsonData() async {
    final responce = json.decode(await getLocalJson());
    List tempList = new List();
    for (var i in responce['data']) {
      tempList.add(i);   // Create a list and add data one by one 
    }
    fullData = tempList;
  }

  onSearchTextChanged(String text) async {
    searchData.clear();
    if (text.isEmpty) {    // Check textfield is empty or not 
      setState(() {});
      return;
    }

    fullData.forEach((data) {
      if (data['Title']
          .toString()
          .toLowerCase()
          .contains(text.toLowerCase().toString())) {
        searchData.add(data);   // If not empty then add search data into search data list 
      }
    });

    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: InkWell(
          child: Text("Search With Local Data"),
        ),
      ),
      body: Container(
          child: Column(
        children: [
          TextField(
            controller: textEditingController,
            onChanged: onSearchTextChanged,
          ),
          Expanded(
            child: searchData.length == 0   // Check SearchData list is empty or not if empty then show full data else show search data
                ? ListView.builder(
                    itemCount: fullData.length,
                    itemBuilder: (context, int index) {
                      return Container(
                        decoration: BoxDecoration(
                            color: Colors.white,
                            boxShadow: [
                              BoxShadow(
                                  color: Colors.grey,
                                  spreadRadius: 2,
                                  offset: Offset(2, 2))
                            ]),
                        margin: EdgeInsets.all(10),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              "Post",
                              style: TextStyle(
                                  fontWeight: FontWeight.bold, fontSize: 16),
                            ),
                            Container(
                              height: 2,
                            ),
                            Text(fullData[index]['Title'])
                          ],
                        ),
                      );
                    },
                  )
                : ListView.builder(
                    itemCount: searchData.length,
                    itemBuilder: (context, int index) {
                      return Container(
                        decoration: BoxDecoration(
                            color: Colors.white,
                            boxShadow: [
                              BoxShadow(
                                  color: Colors.grey,
                                  spreadRadius: 2,
                                  offset: Offset(2, 2))
                            ]),
                        margin: EdgeInsets.all(10),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              "Post",
                              style: TextStyle(
                                  fontWeight: FontWeight.bold, fontSize: 16),
                            ),
                            Container(
                              height: 2,
                            ),
                            Text(searchData[index]['Title'])
                          ],
                        ),
                      );
                    },
                  ),
          )
        ],
      )),
    );
  }
}

这是我的本地数据。json 文件

{
  "data": [
    {
      "Id": 1,
      "Title": "ABC",
      "Body": "And it takes nsuscipit follow accepted lightly with nreprehenderit discomfort may be the entire nnostrum of the things that happens is that they are extremely"
    },
    {
      "Id": 1,
      "Title": "CDF",
      "Body": "And it takes nsuscipit follow accepted lightly with nreprehenderit discomfort may be the entire nnostrum of the things that happens is that they are extremely"
    },
    {
      "Id": 1,
      "Title": "EFG",
      "Body": "And it takes nsuscipit follow accepted lightly with nreprehenderit discomfort may be the entire nnostrum of the things that happens is that they are extremely"
    },
    {
      "Id": 1,
      "Title": "ABCD",
      "Body": "And it takes nsuscipit follow accepted lightly with nreprehenderit discomfort may be the entire nnostrum of the things that happens is that they are extremely"
    },
    {
      "Id": 1,
      "Title": "PQR",
      "Body": "And it takes nsuscipit follow accepted lightly with nreprehenderit discomfort may be the entire nnostrum of the things that happens is that they are extremely"
    },
    {
      "Id": 1,
      "Title": "RNDS",
      "Body": "And it takes nsuscipit follow accepted lightly with nreprehenderit discomfort may be the entire nnostrum of the things that happens is that they are extremely"
    },
    {
      "Id": 1,
      "Title": "qwer",
      "Body": "And it takes nsuscipit follow accepted lightly with nreprehenderit discomfort may be the entire nnostrum of the things that happens is that they are extremely"
    },
    {
      "Id": 1,
      "Title": "asdad",
      "Body": "And it takes nsuscipit follow accepted lightly with nreprehenderit discomfort may be the entire nnostrum of the things that happens is that they are extremely"
    }
  ]
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM