Introduction:
Adding a search bar to your Flutter app enhances user experience by enabling them to efficiently search and filter content. In this tutorial, we’ll guide you through the process of seamlessly integrating a search bar into your Flutter application.
Content:
1. Create a New Flutter Project
Ensure Flutter is installed on your machine. Create a new Flutter project using the following terminal command:
flutter create search_bar_example
2. Add Required Dependencies
Open your pubspec.yaml
file and include the necessary dependencies:
dependencies:
flutter:
sdk: flutter
# Add other dependencies as needed
Fetch the new dependency by running the following command:
flutter pub get
3. Implement the Search Bar
In the Dart file where you want the search bar, import the necessary packages:
import 'package:flutter/material.dart';
import 'package:flutter/material.dart';
Create a stateful widget with the main app structure:
class SearchBarExample extends StatefulWidget {
@override
_SearchBarExampleState createState() => _SearchBarExampleState();
}
class _SearchBarExampleState extends State<SearchBarExample> {
// Add your state variables and methods here
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Search Bar Example'),
actions: [
IconButton(
icon: Icon(Icons.search),
onPressed: () {
// Handle search button press
},
),
],
),
body: Center(
child: Text('Your App Content Goes Here'),
),
);
}
}
void main() {
runApp(MaterialApp(
home: SearchBarExample(),
));
}
4. Add Search Functionality
Extend the implementation by adding search functionality using a TextField
widget:
class _SearchBarExampleState extends State<SearchBarExample> {
TextEditingController _searchController = TextEditingController();
String _searchQuery = '';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Search Bar Example'),
actions: [
IconButton(
icon: Icon(Icons.search),
onPressed: () {
showSearch(
context: context,
delegate: CustomSearchDelegate(),
);
},
),
],
),
body: Center(
child: Text('Your App Content Goes Here'),
),
);
}
}
class CustomSearchDelegate extends SearchDelegate<String> {
@override
List<Widget> buildActions(BuildContext context) {
return [
IconButton(
icon: Icon(Icons.clear),
onPressed: () {
query = '';
},
),
];
}
@override
Widget buildLeading(BuildContext context) {
return IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () {
close(context, '');
},
);
}
@override
Widget buildResults(BuildContext context) {
// Implement search results display based on the query
return Center(
child: Text('Search Results for: $query'),
);
}
@override
Widget buildSuggestions(BuildContext context) {
// Implement search suggestions based on the query
return Center(
child: Text('Search Suggestions for: $query'),
);
}
}
5. Customize and Test
Customize the search bar and functionality according to your app’s requirements. Add additional features, such as filtering data based on user input.
Save your changes and run the app:
flutter run
Upon running the app, you should see the search bar in the app bar. Customize the content and functionality based on your specific use case.
Sample Code:
import 'package:flutter/material.dart';
class SarchbarPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.blue,
centerTitle: true,
title: Text('Search Bar Page'),
actions: [
IconButton(
icon: Icon(Icons.search),
onPressed: () {
showSearch(useRootNavigator: false, context: context, delegate: CustomSearchDelegate());
},
),
],
),
body: Center(
child: Text('Home Page Content'),
),
);
}
}
class CustomSearchDelegate extends SearchDelegate<String> {
@override
List<Widget> buildActions(BuildContext context) {
return [
IconButton(
icon: Icon(Icons.clear),
onPressed: () {
query = '';
},
),
];
}
@override
Widget buildLeading(BuildContext context) {
return IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () {
close(context, null!);
},
);
}
@override
Widget buildResults(BuildContext context) {
// Implement the search results here based on the query.
return Center(
child: Text('Search results for: $query'),
);
}
@override
Widget buildSuggestions(BuildContext context) {
// Implement suggestions here based on the query.
final List<String> suggestionList = [
"Oliver Anderson",
"Sophia Martinez",
"Liam Johnson",
"Emma Smith",
"Noah Davis",
"Ava Taylor",
"Ethan Brown",
"Isabella Wilson",
"Lucas Moore",
"Mia Jones",
"Jackson Robinson",
"Olivia White",
"Aiden Harris",
"Sophia Thompson",
"Logan Carter",
"Emily Miller",
"Mason Martin",
"Harper Clark",
"Caleb Turner",
"Chloe Baker",
];
final filteredList = suggestionList.where((suggestion) => suggestion.toLowerCase().contains(query.toLowerCase())).toList();
return ListView.builder(
itemCount: filteredList.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(filteredList[index]),
onTap: () {
// You can handle the selection of a suggestion here.
// For example, you might want to navigate to a new page.
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SearchResultPage(query: filteredList[index]),
),
);
},
);
},
);
}
}
class SearchResultPage extends StatelessWidget {
final String query;
SearchResultPage({required this.query});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Search Result'),
),
body: Center(
child: Text('Search result for: $query'),
),
);
}
}
Output:
Conclusion:
Congratulations! You have successfully implemented a search bar in your Flutter app. Enhance the user experience by allowing users to search and filter content seamlessly within your application.