Flutter / GetX Steps / Step5: Working with API
Working with API
-
Fetch Data: without model
1. controller page
import 'package:get/get.dart'; import 'package:http/http.dart' as http; class ApiService { Future fetchData() async { final response = await http.get(Uri.parse('https://randomuser.me/api/?results=20')); if (response.statusCode == 200) { // If the server returns a 200 OK response, parse the JSON. return response.body; } else { // If the server did not return a 200 OK response, throw an exception. throw Exception('Failed to load data'); } } } class LoginController extends GetxController { final ApiService _apiService = ApiService(); var data = ''.obs; @override void onInit() { fetchData(); super.onInit(); } Future fetchData() async { try { var fetchedData = await _apiService.fetchData(); data.value = fetchedData; } catch (e) { // Handle errors here print(e); } } } 2. view page
import 'package:flutter/material.dart'; import 'package:vera/controllers/login_controller.dart'; import 'package:get/get.dart'; class LoginPage extends StatelessWidget { @override final LoginController dataController = Get.put(LoginController()); Widget build(BuildContext context) { return GetBuilder ( builder: (controller) => Scaffold( body: Center( child: Obx( () => Text( dataController.data.value, style: TextStyle(fontSize: 24), ), ), ), ) ); } } -
Fetch Data: with model
1. Model
lib/models/user_model.dart
class UserModel { int? id; String? email; String? firstName; String? lastName; String? avatar; UserModel({this.id, this.email, this.firstName, this.lastName, this.avatar}); UserModel.fromJson(Map json) { id = json['id']; email = json['email']; firstName = json['first_name']; lastName = json['last_name']; avatar = json['avatar']; } } 2. controller
1. load model
import 'package:vera/models/user_model.dart'; 2. define variables
var userList = [].obs; var isLoading = true.obs; 3. define api function
Future getUsers() async { const String userUrl = "https://reqres.in/api/users?page=2"; final response = await http.get(Uri.parse(userUrl)); if (response.statusCode == 200) { final List result = jsonDecode(response.body)['data']; userList.value = result.map((e) => UserModel.fromJson(e)).toList(); isLoading.value = false; update(); } else { Get.snackbar('Error Loading data!', 'Sever responded: ${response.statusCode}:${response.reasonPhrase.toString()}'); } } 4. call api function
@override void onInit() { super.onInit(); getUsers(); } /pre> Complete codeimport 'package:get/get.dart'; import 'dart:convert'; import 'package:http/http.dart' as http; import 'package:vera/models/user_model.dart'; class LoginController extends GetxController { var userList = [].obs; var isLoading = true.obs; Future getUsers() async { const String userUrl = "https://reqres.in/api/users?page=2"; final response = await http.get(Uri.parse(userUrl)); if (response.statusCode == 200) { final List result = jsonDecode(response.body)['data']; userList.value = result.map((e) => UserModel.fromJson(e)).toList(); isLoading.value = false; update(); } else { Get.snackbar('Error Loading data!', 'Sever responded: ${response.statusCode}:${response.reasonPhrase.toString()}'); } } @override void onInit() { super.onInit(); getUsers(); } } 3. in view
1. load model
import 'package:vera/models/user_model.dart'; 2. define controller variable
final LoginController controller = Get.put(LoginController()); 3. define model object
List userList = controller.userList; 4. create view body
Complete codeObx( () => controller.isLoading.value ? const Center(child: CircularProgressIndicator()) : ListView.builder( itemCount: userList.length, itemBuilder: (_, index) { return Padding( padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 8), child: Card( color: Theme.of(context).primaryColor, child: ListTile( title: Text( '${userList[index].firstName} ${userList[index].lastName}', style: const TextStyle(color: Colors.white), ), subtitle: Text( '${userList[index].email}', style: const TextStyle(color: Colors.white), ), leading: CircleAvatar( backgroundImage: NetworkImage( userList[index].avatar.toString()), ), ), ), ); }, ), ), import 'package:flutter/material.dart'; import 'package:vera/controllers/login_controller.dart'; import 'package:get/get.dart'; import 'package:vera/models/user_model.dart'; class LoginPage extends StatelessWidget { @override final LoginController controller = Get.put(LoginController()); Widget build(BuildContext context) { List userList = controller.userList; return GetBuilder ( builder: (controller) => Scaffold( body: Obx( () => controller.isLoading.value ? const Center(child: CircularProgressIndicator()) : ListView.builder( itemCount: userList.length, itemBuilder: (_, index) { return Padding( padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 8), child: Card( color: Theme.of(context).primaryColor, child: ListTile( title: Text( '${userList[index].firstName} ${userList[index].lastName}', style: const TextStyle(color: Colors.white), ), subtitle: Text( '${userList[index].email}', style: const TextStyle(color: Colors.white), ), leading: CircleAvatar( backgroundImage: NetworkImage( userList[index].avatar.toString()), ), ), ), ); }, ), ), ) ); } } -
Form
1. add UI widgets ( Button)
open lib/view/login_page.dart
Widget build(BuildContext context) { return GetBuilder ( builder: (controller) => Scaffold( appBar: AppBar( title: const Text('Login'), ), body: Column( children: [ TextButton( style: ButtonStyle( foregroundColor: MaterialStateProperty.all (Colors.blue), ), onPressed: () { }, child: Text('Send Data'), ), TextButton( style: ButtonStyle( foregroundColor: MaterialStateProperty.all (Colors.blue), ), onPressed: () { }, child: Text('Get Data'), ) ] ), ), ); } 2. Integrate API
Let us declare connection string GetConnect()
class LoginPage extends StatelessWidget { final _connect = GetConnect(); Define a function for sending / posting data to API
void _sendPostRequest() async { final response = await _connect.post( 'https://jsonplaceholder.typicode.com/posts', { 'title': 'one two three', 'body': 'four five six seven', 'userId': 1, }, ); print(response.body); } Define a function for getting data from API
void _sendGetRequest() async { final response = await _connect.get('https://jsonplaceholder.typicode.com/posts/1'); print(response.body); } call the function in button onPress()
onPressed: _sendPostRequest, Complete code
import 'package:flutter/material.dart'; import 'package:manoj1/controllers/login_controller.dart'; import 'package:get/get.dart'; class LoginPage extends StatelessWidget { final _connect = GetConnect(); void _sendPostRequest() async { final response = await _connect.post( 'https://jsonplaceholder.typicode.com/posts', { 'title': 'one two three', 'body': 'four five six seven', 'userId': 1, }, ); //if (kDebugMode) { print(response.body); //} } void _sendGetRequest() async { final response = await _connect.get('https://jsonplaceholder.typicode.com/posts/1'); print(response.body); } @override Widget build(BuildContext context) { return GetBuilder ( builder: (controller) => Scaffold( appBar: AppBar( title: const Text('Login'), ), body: Column( children: [ TextButton( style: ButtonStyle( foregroundColor: MaterialStateProperty.all (Colors.blue), ), onPressed: _sendPostRequest, child: Text('Send Data'), ), TextButton( style: ButtonStyle( foregroundColor: MaterialStateProperty.all (Colors.blue), ), onPressed: _sendGetRequest, child: Text('Get Data'), ) ] ), ), ); } } 3. Send Input field data to API
Add textFields - email and password
TextField( controller: emailController, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Email', ), ), TextField( controller: passwordController, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Password', ), ), Complete code
@override Widget build(BuildContext context) { return GetBuilder ( builder: (controller) => Scaffold( appBar: AppBar( title: const Text('Login'), ), body: Column( children: [ TextField( controller: emailController, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Email', ), ), TextField( controller: passwordController, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Password', ), ), TextButton( style: ButtonStyle( foregroundColor: MaterialStateProperty.all (Colors.blue), ), onPressed: _sendPostRequest, child: Text('Send Data'), ), TextButton( style: ButtonStyle( foregroundColor: MaterialStateProperty.all (Colors.blue), ), onPressed: _sendGetRequest, child: Text('Get Data'), ) ] ), ), ); } Let us declare TextEditingController for email and password
class LoginPage extends StatelessWidget { final emailController = TextEditingController(); final passwordController = TextEditingController(); ..... ..... Next assign the variable 'emailController' to the controller property of email TextField()
TextField( controller: emailController, ..... Next assign the variable 'passwordController' to the controller property of password TextField()
TextField( controller: passwordController, ..... Complete code
import 'package:flutter/material.dart'; import 'package:manoj1/controllers/login_controller.dart'; import 'package:get/get.dart'; class LoginPage extends StatelessWidget { final _connect = GetConnect(); final emailController = TextEditingController(); final passwordController = TextEditingController(); void _sendPostRequest() async { final response = await _connect.post( 'https://jsonplaceholder.typicode.com/posts', { 'title': 'one two three', 'body': 'four five six seven', 'userId': 1, }, ); //if (kDebugMode) { print(response.body); //} } void _sendGetRequest() async { final response = await _connect.get('https://jsonplaceholder.typicode.com/posts/1'); print(response.body); } @override Widget build(BuildContext context) { return GetBuilder ( builder: (controller) => Scaffold( appBar: AppBar( title: const Text('Login'), ), body: Column( children: [ TextField( controller: emailController, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Full Name', ), ), TextField( controller: passwordController, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Full Name', ), ), TextButton( style: ButtonStyle( foregroundColor: MaterialStateProperty.all (Colors.blue), ), onPressed: _sendPostRequest, child: Text('Send Data'), ), TextButton( style: ButtonStyle( foregroundColor: MaterialStateProperty.all (Colors.blue), ), onPressed: _sendGetRequest, child: Text('Get Data'), ) ] ), ), ); } } Read input field
var email = emailController.text; var pass = passwordController.text; Send email & password In _sendPostRequest()
void _sendPostRequest() async { var email = emailController.text; var password = passwordController.text; final response = await _connect.post( 'https://jsonplaceholder.typicode.com/posts', { 'enail' : email, 'password': password, }, ); //if (kDebugMode) { print(response.body); //} }