How do I search through data in flutter app

349

First your JSON file will return as a Map, according to this answer at

Unhandled Exception: InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>

for your problem, here is the solution. First you need create a model like this, can be place at separate file or can be place at same file too

class Sports {
  int id;
  String name;

  Sports({
    this.id,
    this.name,
  });

  factory Sports.fromJson(Map<String, dynamic> json) {
    return Sports(id: json['id'], name: json['name']);
  }
}

than here it's the main.dart

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

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

class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

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

class _MyHomePageState extends State<MyApp> {
  TextEditingController controller = new TextEditingController();
  List<Sports> array = [];
  List<Sports> _filtered = [];
  List<Sports> _null_filtered = [];
  String jsonTest =
      '{"success": "true","data": [{"id": 1,"name": "football"},{"id": 2,"name": "rugby"},{"id": 3,"name": "basketball"},{"id": 4,"name": "hockey"},{"id": 5,"name": "tennis"},{"id": 6,"name": "golf"}]}';

  void initState() {
    super.initState();
    test();
  }

  void _alterfilter(String query) {
    List<Sports> dummySearchList = [];
    dummySearchList.addAll(_filtered);
    if (query.isNotEmpty) {
      List<Sports> dummyListData = [];
      dummySearchList.forEach((item) {
        if (item.name.contains(query)) { //if you want to search it order by id you can change item.name.contains to item.id.contains
          dummyListData.add(item);
        }
      });
      setState(() {
        _filtered.clear();
        _filtered.addAll(dummyListData); //dummyListData will place all the data that match at your search bar
      });
      return;
    } else {
      setState(() {
        _filtered.clear();
        _filtered.addAll(_null_filtered); //_null_filtered will place all the data if search bar was empty after enter a words
      });
    }
  }

  Future<Sports> test() async {
    Map<String, dynamic> tagObjsJson = json.decode(jsonTest);
    List<dynamic> data = tagObjsJson["data"];
    setState(() {
      for (Map Data in data) {
        array.add(Sports.fromJson(Data));
      }
      _filtered.addAll(array);
      _null_filtered.addAll(array);
      for (int a = 0; a < _filtered.length; a++) {
        print(_filtered[a].name);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Container(
                  alignment: Alignment.center,
                  child: Container(
                    margin: const EdgeInsets.only(top: 50),
                    width: 300,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(20),
                        border: Border.all(
                            width: 1,
                            color: Color.fromRGBO(11, 189, 180, 1),
                            style: BorderStyle.solid)),
                    child: TextField(
                      decoration: InputDecoration(
                          hintText: 'Search your data',
                          contentPadding: EdgeInsets.all(15),
                          border: InputBorder.none),
                      controller: controller,
                      onChanged: (value) {
                        _alterfilter(value);
                      },
                    ),
                  ),
                ),
              ],
            ),
            Expanded(
                child: Container(
              margin: const EdgeInsets.all(20),
              child: ListView.builder(
                scrollDirection: Axis.vertical,
                shrinkWrap: true,
                itemCount: _filtered.length,
                itemBuilder: (context, index) {
                  if (array.length > 0) {
                    final x = _filtered[index];
                    final y = _filtered[index].id.toString();
                    return ListTile(
                      title: Text(y),
                      subtitle: Text(x.name),
                    );
                  }
                },
              ),
            ))
          ],
        ),
      ),
    ));
  }
}

Sorry mate if my english was very bad but tell me if you got confused

the result the result after input search bar

Share:
349
Admin
Author by

Admin

Updated on December 28, 2022

Comments

  • Admin
    Admin over 1 year

    I am new to flutter and I was following a tutorial that shows how to search through data. I cannot recreate that using my own example. I would like to know how to search through data in a ListView from this json data.

    
    {
    
        "success": "true",
        "data": [
            {
                "id": 1,
                "name": "football"
            },
            {
                "id": 2,
                "name": "rugby"
            },
            {
                "id": 3,
                "name": "basketball"
            },
            {
                "id": 4,
                "name": "hockey"
            },
            {
                "id": 5,
                "name": "tennis"
            },
            {
                "id": 6,
                "name": "golf"
            }
        ]
    
    }
    

    Displayed using this code

                if (snapshot.hasData) {
                  return ListView.builder(
                    itemCount: sports.games.length,
                    itemBuilder: (context, index) {
                      if (sports.games.length > 0) {
                        final x = sports.games[index];
                        final y = sports.games[index].id.toString();
                        return ListTile(
                          title: Text(y),
                          subtitle: Text(x.name),
                        );
                      }
                    },
                  );
                }
              },
    
  • Admin
    Admin about 3 years
    I understood you well, this is fine. Thanks