Flutter / GetX Basics / Searchbox in one screen and result in another screen
Searchbox and result in two sreeens
-
Code
You can implement a search functionality using GetX in Flutter and display the search results on another page. Here's an example to guide you through this process:
Let's start by creating a simple app structure with two screens: the search screen and the result screen.
Search Screen:This screen contains a text field for inputting the search query and a button to trigger the search.
Result Screen:This screen displays the search results fetched from the API.
import 'package:flutter/material.dart'; import 'package:get/get.dart'; void main() { runApp(MyApp()); } class DataController extends GetxController { var searchResults = [].obs; void fetchSearchResults(String query) async { // Perform API request here (replace with your actual API request logic) // For demonstration purposes, it's left empty. // Once you have actual API data, update the searchResults. // Example: final response = await http.get('your_api_url'); // Then parse and assign data to searchResults. searchResults.value = []; } } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return GetMaterialApp( initialRoute: '/', getPages: [ GetPage(name: '/', page: () => SearchScreen()), GetPage(name: '/result', page: () => ResultScreen()), ], ); } } class SearchScreen extends StatelessWidget { final DataController dataController = Get.put(DataController()); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Search Screen'), ), body: Padding( padding: EdgeInsets.all(16.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ TextField( onChanged: (value) { // Update the query in the controller dataController.fetchSearchResults(value); }, decoration: InputDecoration( labelText: 'Search', border: OutlineInputBorder(), ), ), SizedBox(height: 20), ElevatedButton( onPressed: () { // Navigate to the result screen Get.toNamed('/result'); }, child: Text('Search'), ), ], ), ), ); } } class ResultScreen extends StatelessWidget { final DataController dataController = Get.put(DataController()); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Result Screen'), ), body: Obx(() { final searchResults = dataController.searchResults; return ListView.builder( itemCount: searchResults.length, itemBuilder: (context, index) { final result = searchResults[index]; return ListTile( title: Text(result['title']), // Replace with your actual data structure // Add onTap logic for each search result onTap: () { // Handle tap on search result print('Tapped on: ${result['title']}'); }, ); }, ); }), ); } }