Search code examples
flutterdartsearchbar

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


Hello friend I am retrieve json data in my list view this json file inside my assets folder now I want implement search bar in my flutter application please help how to resolve this this issue its very important part in my app I have 500+ words in my flutter application so user search specific word through search bar any expert is here who can help me

    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
                       ),),
                     ),

                   ],

                 ),

               );
             }
              ),
        )
    );
  }
}

Solution

  • So I just made a code for search data using the local JSON file. First I created an empty list and all data in that list one by one and created a listview. After that created a TextField and check if textfield is empty then show full data else added search data in another list and show this data on 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'])
                              ],
                            ),
                          );
                        },
                      ),
              )
            ],
          )),
        );
      }
    }
    

    And here is my local data.json file

    {
      "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"
        }
      ]
    }