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
Certainly! Below is a step-by-step guide to creating a simple Flutter app with a search bar that sends a GET request to an API endpoint based on the user's input. In this example, when a user types "hello" and submits the search, the app will send a GET request to
http://localhost:8000/search?query=hello.Prerequisites
-
Flutter Installed: Ensure you have Flutter installed on your machine. If not, follow the Flutter installation guide.
-
API Endpoint: Make sure your API server is running on
localhost:8000and has an endpoint/searchthat accepts aqueryparameter.
Step 1: Create a New Flutter Project
Open your terminal or command prompt and run:
flutter create search_appNavigate to the project directory:
cd search_appStep 2: Add Required Dependencies
We'll use the
httppackage to handle HTTP requests. Openpubspec.yamland add thehttpdependency:dependencies: flutter: sdk: flutter http: ^0.13.5Then, run:
flutter pub getStep 3: Update
main.dartReplace the contents of
lib/main.dartwith the following code:import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; // For JSON decoding void main() { runApp(SearchApp()); } class SearchApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Search App', theme: ThemeData( primarySwatch: Colors.blue, ), home: SearchPage(), ); } } class SearchPage extends StatefulWidget { SearchPage({Key? key}) : super(key: key); @override _SearchPageState createState() => _SearchPageState(); } class _SearchPageState extends State<SearchPage> { final TextEditingController _controller = TextEditingController(); String _searchResult = ''; bool _isLoading = false; String _errorMessage = ''; Future<void> _performSearch(String query) async { setState(() { _isLoading = true; _errorMessage = ''; _searchResult = ''; }); final uri = Uri.parse('http://localhost:8000/search').replace(queryParameters: {'query': query}); try { final response = await http.get(uri); if (response.statusCode == 200) { // Assuming the API returns JSON. Adjust according to your API's response. final data = json.decode(response.body); setState(() { _searchResult = data.toString(); }); } else { setState(() { _errorMessage = 'Error: ${response.statusCode}'; }); } } catch (e) { setState(() { _errorMessage = 'An error occurred: $e'; }); } finally { setState(() { _isLoading = false; }); } } void _onSearch() { final query = _controller.text.trim(); if (query.isNotEmpty) { _performSearch(query); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Search App'), ), body: Padding( padding: const EdgeInsets.all(16.0), child: Column( children: [ Row( children: [ Expanded( child: TextField( controller: _controller, decoration: InputDecoration( labelText: 'Search', border: OutlineInputBorder(), ), onSubmitted: (value) => _onSearch(), ), ), SizedBox(width: 8), ElevatedButton( onPressed: _onSearch, child: Text('Search'), ), ], ), SizedBox(height: 20), _isLoading ? CircularProgressIndicator() : _errorMessage.isNotEmpty ? Text( _errorMessage, style: TextStyle(color: Colors.red), ) : _searchResult.isNotEmpty ? Expanded( child: SingleChildScrollView( child: Text(_searchResult), ), ) : Container(), ], ), )); } }Step 4: Run the App
Before running the app, ensure that your API server is running on
localhost:8000. Since Flutter apps running on emulators or simulators can accesslocalhostdirectly, this setup should work seamlessly.For Android Emulator:
Simply run:
flutter runFor iOS Simulator:
Similarly, run:
flutter runFor Physical Devices:
Accessing
localhostmay not work as expected becauselocalhostwill refer to the device itself. Instead, use your machine's local IP address.- Find your machine's IP address (e.g.,
192.168.1.100). - Update the API URL in the code:
final uri = Uri.parse('http://192.168.1.100:8000/search').replace(queryParameters: {'query': query});- Ensure that your machine and device are on the same network and that the firewall allows incoming connections on port
8000.
Step 5: Testing the Search Functionality
- Launch the app on your emulator, simulator, or device.
- Enter a search term like
helloin the search bar. - Press the Search button or submit via the keyboard.
- The app will display the response from the API below the search bar.
Additional Considerations
1. Handling CORS (Cross-Origin Resource Sharing)
If your API server is not configured to handle CORS requests, you might encounter issues, especially when testing on web platforms. Ensure your backend API includes the necessary CORS headers. For example, in a Python Flask API, you can use the
flask-corspackage:from flask import Flask from flask_cors import CORS app = Flask(__name__) CORS(app) # Your routes here2. Error Handling and User Feedback
The provided code includes basic error handling. Depending on your use case, you might want to enhance it by providing more detailed feedback or retry mechanisms.
3. UI Enhancements
For a better user experience, consider adding features like:
- Debouncing: To prevent sending a request on every keystroke.
- Clear Button: To quickly clear the search field.
- Results List: If the API returns a list of items, display them using
ListView.
4. Secure Storage of API URLs
For production apps, avoid hardcoding API URLs. Use environment variables or configuration files to manage different environments (development, staging, production).
Complete Code Listing
For your convenience, here's the complete
main.dartfile:import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; // For JSON decoding void main() { runApp(SearchApp()); } class SearchApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Search App', theme: ThemeData( primarySwatch: Colors.blue, ), home: SearchPage(), ); } } class SearchPage extends StatefulWidget { SearchPage({Key? key}) : super(key: key); @override _SearchPageState createState() => _SearchPageState(); } class _SearchPageState extends State<SearchPage> { final TextEditingController _controller = TextEditingController(); String _searchResult = ''; bool _isLoading = false; String _errorMessage = ''; Future<void> _performSearch(String query) async { setState(() { _isLoading = true; _errorMessage = ''; _searchResult = ''; }); final uri = Uri.parse('http://localhost:8000/search').replace(queryParameters: {'query': query}); try { final response = await http.get(uri); if (response.statusCode == 200) { // Assuming the API returns JSON. Adjust according to your API's response. final data = json.decode(response.body); setState(() { _searchResult = data.toString(); }); } else { setState(() { _errorMessage = 'Error: ${response.statusCode}'; }); } } catch (e) { setState(() { _errorMessage = 'An error occurred: $e'; }); } finally { setState(() { _isLoading = false; }); } } void _onSearch() { final query = _controller.text.trim(); if (query.isNotEmpty) { _performSearch(query); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Search App'), ), body: Padding( padding: const EdgeInsets.all(16.0), child: Column( children: [ Row( children: [ Expanded( child: TextField( controller: _controller, decoration: InputDecoration( labelText: 'Search', border: OutlineInputBorder(), ), onSubmitted: (value) => _onSearch(), ), ), SizedBox(width: 8), ElevatedButton( onPressed: _onSearch, child: Text('Search'), ), ], ), SizedBox(height: 20), _isLoading ? CircularProgressIndicator() : _errorMessage.isNotEmpty ? Text( _errorMessage, style: TextStyle(color: Colors.red), ) : _searchResult.isNotEmpty ? Expanded( child: SingleChildScrollView( child: Text(_searchResult), ), ) : Container(), ], ), )); } }Conclusion
You've now created a basic Flutter app with a search bar that sends a GET request to an API based on user input. From here, you can expand the app's functionality by handling different types of responses, enhancing the UI, adding authentication, and more. Flutter's versatility allows you to build sophisticated applications with relative ease. Happy coding!
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.