Implementing a Search Functionality

This example shows how to create a search feature using a TextField to filter a list of items.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
return MaterialApp(
  title: 'Search Example',
  theme: ThemeData(primarySwatch: Colors.blue),
  home: SearchExample(),
);
} } class SearchExample extends StatefulWidget { @override _SearchExampleState createState() => _SearchExampleState(); } class _SearchExampleState extends State<SearchExample> { final List<String> _items = [
'Apple',
'Banana',
'Cherry',
'Date',
'Fig',
'Grapes',
'Orange',
'Peach',
'Pineapple',
'Strawberry',
]; List<String> _filteredItems = []; String _searchQuery = ''; @override void initState() {
super.initState();
_filteredItems = _items;
} void _filterItems(String query) {
if (query.isNotEmpty) {
  setState(() {
    _searchQuery = query;
    _filteredItems = _items
        .where((item) => item.toLowerCase().contains(query.toLowerCase()))
        .toList();
  });
} else {
  setState(() {
    _searchQuery = '';
    _filteredItems = _items;
  });
}
} @override Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(title: Text('Search Example')),
  body: Padding(
    padding: const EdgeInsets.all(16.0),
    child: Column(
      children: &#91;
        TextField(
          onChanged: _filterItems,
          decoration: InputDecoration(
            labelText: 'Search',
            border: OutlineInputBorder(),
          ),
        ),
        SizedBox(height: 10),
        Expanded(
          child: ListView.builder(
            itemCount: _filteredItems.length,
            itemBuilder: (context, index) {
              return ListTile(
                title: Text(_filteredItems&#91;index]),
              );
            },
          ),
        ),
      ],
    ),
  ),
);
} }

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *