1. pubspec.yaml
dependencies:
flutter:
sdk: flutter
get: ^4.6.1 # Ensure you have the latest GetX version
http: ^0.14.0 # HTTP package for making API requests
2. screen
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(MyApp());
}
class DataController extends GetxController {
var searchResults = [].obs;
void fetchSearchResults(String query) async {
final response = await http.get(Uri.parse('https://api.example.com/search?q=$query'));
if (response.statusCode == 200) {
final data = json.decode(response.body);
searchResults.value = data['results'];
} else {
// Handle error scenarios
searchResults.value = [];
}
}
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GetMaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
final DataController dataController = Get.put(DataController());
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Search Example'),
),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
children: [
TextField(
onChanged: (value) {
dataController.fetchSearchResults(value); // Fetch data on text change
},
decoration: InputDecoration(
labelText: 'Search',
border: OutlineInputBorder(),
),
),
SizedBox(height: 20),
Expanded(
child: Obx(() {
// Obx widget will automatically rebuild when searchResults change
final searchResults = dataController.searchResults;
return ListView.builder(
itemCount: searchResults.length,
itemBuilder: (context, index) {
final result = searchResults[index];
return ListTile(
title: Text(result['title']), // Assuming 'title' field in result data
// Add onTap logic for each search result
onTap: () {
// Handle tap on search result
print('Tapped on: ${result['title']}');
},
);
},
);
}),
),
],
),
),
);
}
}