0

Code :

            class MobileCourses extends StatefulWidget {   const MobileCourses({ Key? key }) : super(key: key);
            
              @override   _MobileCoursesState createState() =>
            _MobileCoursesState(); }
            
            class _MobileCoursesState extends State<MobileCourses> {   String searchCourse = "";   TextEditingController searchController = TextEditingController();   @override   Widget build(BuildContext context) {
                return Scaffold(
                  body: Column(
                    children: [
                      searchBar(),
                      Expanded(
                          child: Container(
                          padding: EdgeInsets.all(15),
                          child : FutureBuilder(
                            future: Networking.getAllCourses(),
                            
                            builder: (_,snapshot)
                            {
                           
                              if(snapshot.hasData)
                              {
                               
                                List<SpecificCourse>? specificCourse = snapshot.data as List<SpecificCourse>?;
                                return GridView.builder(
                                  physics: BouncingScrollPhysics(),
                                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                                    crossAxisCount: 2,
                                    mainAxisSpacing: 15,
                                    crossAxisSpacing: 15
                                  ),
                                  itemCount: specificCourse![0].courses.length ,
                                  
                                  itemBuilder: (_,index)
                                  {
                                   return specificCourse[0].courses[index].course.toLowerCase().contains(searchCourse) ? MobileContainer(course: specificCourse[0].courses[index].course):Container(color: Colors.red,), 
// over here i am searching for my required course
                                                                        
                                  },
                                );
                              }
                              else
                              {
                                return  CircularProgressIndicator();
                              }
                            }
                          ),
                        ),
                      ),
                    ],
                  ),
                );   
        }   
        }
    

Search Bar :-

Widget searchBar()   {
                return Padding(
                  padding: const EdgeInsets.only(left : 15.0,right: 15.0 , top: 10.0 ,bottom: 10.0),
                  child: Container(
                    child: TextField(
                      decoration: InputDecoration(
                        hintText: "Search...",
                        prefixIcon: Icon(Icons.search)
                      ),
                      onChanged: (value){
                        setState(() {
                          searchCourse = value.toLowerCase();
                        });
                      },
                      controller: searchController,
                    ),
                  ),
                );  
             }

I want to implement search function inside my gridview and i have tried to implement it in the above code and the ui is looking something like this

enter image description here

but when i search "m" it should return me only MBA but it is returning container too i do not want these container(colored in red) i only want MBA .......I have explicity given container red for better understanding

enter image description here

Container without red color enter image description here

i only want to return MBA but the empty container is consuming space. Please help ! and sorry for these big images i do not know how to decrease their size

4
  • can you add SpecificCourse, Networking.getAllCourses(),, and MobileContainer Commented Aug 2, 2021 at 14:06
  • @YeasinSheikh i have edited and added all the classes and function that you have asked for . Commented Aug 2, 2021 at 14:19
  • 1
    check this answer,i had same issue,this will give some idea stackoverflow.com/a/68530177/13418165@Siddharth Commented Aug 4, 2021 at 7:49
  • @Assassin thanks for commenting and helping me .......... answer to your question helped me and now my problem is solved after seeing answer to your question ......as an appreciation i am voting up your question and solution both and thanks again : ) Commented Aug 7, 2021 at 6:40

1 Answer 1

2

Try to below code its working for me for ListView.Builder Please try to change it Gridview hope it helps you:

Create one class with your JSON Data :

class User {
  String name;
  int id;
  int totalLeads;
  User({
    this.id,
    this.name,
    this.totalLeads,
  });

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      name: json['name'] as String,
      id: int.parse(json['userId']),
      totalLeads: int.parse(json['total']),
    );
  }
}

Create one class that you declare voidCallback function:

class Debouncer {
  final int milliseconds;
  VoidCallback action;
  Timer _timer;

  Debouncer({this.milliseconds});

  run(VoidCallback action) {
    if (null != _timer) {
      _timer.cancel();
    }
    _timer = Timer(Duration(milliseconds: milliseconds), action);
  }
}


Create Stateful Widget Class

class AllAgents extends StatefulWidget {
      AllAgents() : super();
    
      @override
      AllAgentsState createState() => AllAgentsState();
    }
  




class AllAgentsState extends State<AllAgents> {
final _debouncer = Debouncer(milliseconds: 500);
 List<User> users = [];
List<User> filteredUsers = [];
static String url = 'your API url here';


  static Future<List<User>> getAllLeagentsList() async {
    try {
      final response = await http.get(url);
      if (response.statusCode == 200) {
        List<User> list = parseAgents(response.body);

        return list;
      } else {
        throw Exception('Error');
      }
    } catch (e) {
      throw Exception(e.toString());
    }
  }
 static List<User> parseAgents(String responseBody) {
    final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
    return parsed.map<User>((json) => User.fromJson(json)).toList();
  }

  @override
  void initState() {
    super.initState();
    getAllLeagentsList().then((usersFromServer) {
      setState(() {
        users = usersFromServer;
        filteredUsers = users;
      });
    });
  }

// Declare Your Widget here
Column(children:[
 //Search Bar to List of typed User
          Container(
            padding: EdgeInsets.only(top: 20, left: 20, right: 20),
            child: TextField(
              textInputAction: TextInputAction.next,
              decoration: InputDecoration(
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(25.0),
                  borderSide: BorderSide(
                    color: Colors.grey,
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(20.0),
                  borderSide: BorderSide(
                    color: Colors.blue,
                  ),
                ),
                suffixIcon: IconButton(
                  icon: Icon(Icons.search),
                  onPressed: () {},
                ),
                contentPadding: EdgeInsets.all(15.0),
                hintText: 'Search ',
              ),
              onChanged: (string) {
                _debouncer.run(() {
                  setState(() {
                    filteredUsers = users
                        .where((u) => (u.name
                            .toLowerCase()
                            .contains(string.toLowerCase())))
                        .toList();
                  });
                });
              },
            ),
          ),

 //Lists of Agents
          Expanded(
            child: ListView.builder(
              shrinkWrap: true,
              physics: ClampingScrollPhysics(),
              padding: EdgeInsets.only(top: 20, left: 20, right: 20),
              itemCount: filteredUsers.length,
              itemBuilder: (BuildContext context, int index) {
return Card(
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(20),
                          side: BorderSide(
                            color: Colors.grey[300],
                          ),
                        ),
                        child: Padding(
                          padding: EdgeInsets.all(5.0),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              ListTile(
                                leading: Container(
                                  padding: EdgeInsets.all(5.0),
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(8.0),
                                    color: Colors.white,
                                    border: Border.all(color: Colors.blue),
                                    boxShadow: [
                                      BoxShadow(
                                        color: Colors.black,
                                        blurRadius: 2.0,
                                        spreadRadius: 1.0,
                                        offset: Offset(
                                          1.0,
                                          1.0,
                                        ), // shadow direction: bottom right
                                      )
                                    ],
                                  ),
                                  child: Text(filteredUsers[index].name[0]),
                                ),
                                title: Text(
                                  filteredUsers[index].name,
                                  style: TextStyle(fontSize: 16),
                                ),
                                                                
                              )
                            ],
                          ),
                        ),
                      );
},),),
],),

}

here is my screen without search -> First Screen

here is my screen with search ->enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

I appreciate your effort but i think my question has been misunderstood due to first comment so i have edited it again and explaining it again :-
My search functionality is working fine but actual problem you can see those red container's(in photo) those are occupying space with my intended search but do not want those red container to be in my grid i only my intended search result which in this case is MBA
Please feel free to ask any kind of doubt regarding my question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.