Make a flutter app with a search bar, which sends the search query to an api if search…
- User
Make a flutter app with a search bar, which sends the search query to an api if search term is "hello" the search bar will send a get request to api localhost:8000/search?query=hello
- Assistant
To create a Flutter app with a search bar that sends the search query to an API (e.g.,
localhost:8000/search?query=hello), follow these steps:- Set Up a New Flutter Project.
- Add the Required Dependencies.
- Create the UI with a Search Bar.
- Handle User Input and Send GET Request.
- Display the Response.
Let's go through each step in detail.
1. Set Up a New Flutter Project
First, create a new Flutter project by running the following command in your terminal:
flutter create search_appNavigate to the project directory:
cd search_app
2. Add the Required Dependencies
To make HTTP requests, you'll need the
httppackage. Open yourpubspec.yamlfile and add it to your dependencies:dependencies: flutter: sdk: flutter http: ^0.13.6Run
flutter pub getto fetch the package:flutter pub get
3. Create the UI with a Search Bar
Open
lib/main.dartand replace its content with the following code:import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; void main() { runApp(SearchApp()); } class SearchApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Search App', home: SearchPage(), debugShowCheckedModeBanner: false, ); } } class SearchPage extends StatefulWidget { @override _SearchPageState createState() => _SearchPageState(); } class _SearchPageState extends State<SearchPage> { // Controller for the search field final TextEditingController _searchController = TextEditingController(); // Stores the API response String _response = ''; // Function to handle search button press void _handleSearch() async { final query = _searchController.text.trim(); if (query.isEmpty) { // Show a message or handle empty query return; } final url = Uri.parse('http://localhost:8000/search?query=$query'); try { final response = await http.get(url); if (response.statusCode == 200) { setState(() { _response = response.body; }); } else { setState(() { _response = 'Error: ${response.statusCode}'; }); } } catch (e) { setState(() { _response = 'Error: $e'; }); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Search API Example'), ), body: Padding( padding: EdgeInsets.all(16.0), child: Column( children: [ // Search bar TextField( controller: _searchController, decoration: InputDecoration( labelText: 'Enter search query', suffixIcon: IconButton( icon: Icon(Icons.search), onPressed: _handleSearch, ), ), onSubmitted: (value) => _handleSearch(), ), SizedBox(height: 20), // Display the response Expanded( child: SingleChildScrollView( child: Text(_response), ), ), ], ), )); } }
4. Handle User Input and Send GET Request
In the
_handleSearchfunction:- Get the Search Query: Retrieve the text from the
_searchController. - Construct the URL: Create the URI for the GET request.
- Send the GET Request: Use the
httppackage to send the request. - Handle the Response:
- If successful (
statusCode == 200), display the response. - If there's an error, show an error message.
- If successful (
5. Display the Response
In the
Expandedwidget within theColumn, theTextwidget displays the_responsestring, which contains the API response or error message.
Testing the App
Ensure your API is running on
localhost:8000and can handle GET requests to/search.Run your Flutter app:
flutter runNote: If you're testing on a device or emulator, replace
localhostwith your computer's IP address, aslocalhostwill refer to the device/emulator itself.
Handling Localhost Access
To access
localhostfrom an emulator or physical device, you need to use special addresses:- Android Emulator: Use
10.0.2.2instead oflocalhost. - iOS Simulator:
localhostworks as is. - Physical Device: Use your computer's local network IP address.
Example for Android Emulator:
final url = Uri.parse('http://10.0.2.2:8000/search?query=$query');
Complete Code with Emulator Handling
import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; void main() { runApp(SearchApp()); } class SearchApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Search App', home: SearchPage(), debugShowCheckedModeBanner: false, ); } } class SearchPage extends StatefulWidget { @override _SearchPageState createState() => _SearchPageState(); } class _SearchPageState extends State<SearchPage> { // Controller for the search field final TextEditingController _searchController = TextEditingController(); // Stores the API response String _response = ''; // Function to handle search button press void _handleSearch() async { final query = _searchController.text.trim(); if (query.isEmpty) { // Show a message or handle empty query return; } // Adjust the URL based on your testing environment // For Android Emulator, use 10.0.2.2 // For iOS Simulator or physical devices, adjust accordingly final url = Uri.parse('http://10.0.2.2:8000/search?query=$query'); try { final response = await http.get(url); if (response.statusCode == 200) { setState(() { _response = response.body; }); } else { setState(() { _response = 'Error: ${response.statusCode}'; }); } } catch (e) { setState(() { _response = 'Error: $e'; }); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Search API Example'), ), body: Padding( padding: EdgeInsets.all(16.0), child: Column( children: [ // Search bar TextField( controller: _searchController, decoration: InputDecoration( labelText: 'Enter search query', suffixIcon: IconButton( icon: Icon(Icons.search), onPressed: _handleSearch, ), ), onSubmitted: (value) => _handleSearch(), ), SizedBox(height: 20), // Display the response Expanded( child: SingleChildScrollView( child: Text(_response), ), ), ], ), )); } }
Explanation of the Code
-
Imports:
flutter/material.dart: For building the UI.http/http.dart: For sending HTTP requests.
-
Main Function:
- Initializes the app with
SearchApp.
- Initializes the app with
-
SearchApp Class:
- A stateless widget that sets up the
MaterialApp.
- A stateless widget that sets up the
-
SearchPage Class:
- A stateful widget that contains the main functionality.
-
State Variables:
_searchController: To capture user input._response: To store and display the API response.
-
_handleSearch Function:
- Checks if the query is empty.
- Constructs the URI with the query parameter.
- Sends a GET request.
- Updates the UI with the response or error message.
-
Build Method:
- Contains a
Scaffoldwith anAppBar. - The body has a
Columnwith:- A
TextFieldfor input. - A
SizedBoxfor spacing. - An
Expandedwidget with aSingleChildScrollViewto display the response.
- A
- Contains a
Handling JSON Responses
If your API returns JSON data, you can parse it and display it accordingly.
Import the dart:convert Package:
import 'dart:convert';Modify the _handleSearch Function:
void _handleSearch() async { // ... (previous code) try { final response = await http.get(url); if (response.statusCode == 200) { // Parse JSON final data = json.decode(response.body); setState(() { _response = data.toString(); // Or format as needed }); } else { setState(() { _response = 'Error: ${response.statusCode}'; }); } } catch (e) { setState(() { _response = 'Error: $e'; }); } }
Additional Enhancements
-
Loading Indicator:
- Add a loading spinner while the request is in progress.
-
Error Handling:
- Display user-friendly error messages.
- Handle different status codes.
-
Input Validation:
- Validate the search query before sending the request.
-
UI Improvements:
- Enhance the UI with better styling.
- Use
ListViewor other widgets to display structured data.
Conclusion
By following the steps above, you've created a Flutter app with a search bar that sends the user's input as a GET request to an API endpoint like
localhost:8000/search?query=hello. You can now expand upon this foundation to build a more complex search functionality, handle different types of data, and improve the user experience.Let me know if you need further assistance or have any questions!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.