Question for one thing in Flutter with API connection

daddybot

Failed to resolve a dispute resolution thread.
Joined
Feb 28, 2024
Messages
174
Reaction score
103
Not sure how to figure title tbh.

I have API BE which needs to be fetched from flutter mobile app. It needs to fetch cookies (session) save and set on each request for each device. (if you get what im asking)

Is this possible? Im asking this cause some guys are telling its not possible, it needs to be more like getting token in body, but whole BE is made to work with cookies sessions.
 
To handle session-based authentication using cookies with a Flutter mobile app, you'll want to ensure that cookies (usually a session cookie) from your backend API (API BE) are stored and sent with each subsequent request.
 
To handle session-based authentication using cookies with a Flutter mobile app, you'll want to ensure that cookies (usually a session cookie) from your backend API (API BE) are stored and sent with each subsequent request.
yes, but its possible to POST login, save cookies and set them on each request
 
yes, but its possible to POST login, save cookies and set them on each request
Yes, it’s possible to implement a login flow where you POST credentials to log in, save the session cookies on successful authentication, and attach those cookies on each subsequent request.
 
Yes, it’s possible to implement a login flow where you POST credentials to log in, save the session cookies on successful authentication, and attach those cookies on each subsequent request.
is there somewhere sample or if u have sample of how to do it?
i would appreciate help
 
dependencies:
http: ^0.13.4
shared_preferences: ^2.0.7



import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

Future<bool> login(String url, Map<String, String> credentials) async {
try {
final response = await http.post(
Uri.parse(url),
body: credentials,
);

if (response.statusCode == 200) {
// Fetch the 'set-cookie' header from the response
final cookie = response.headers['set-cookie'];
if (cookie != null) {
// Save the cookie in SharedPreferences
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString('cookie', cookie);
return true; // Login successful
}
}
return false; // Login failed or cookie missing
} catch (e) {
print("Login error: $e");
return false; // Error occurred
}
}

Future<http.Response> fetchDataWithCookie(String url) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
final cookie = prefs.getString('cookie');

final headers = {
'Content-Type': 'application/json',
if (cookie != null) 'Cookie': cookie, // Attach the cookie if available
};

final response = await http.get(
Uri.parse(url),
headers: headers,
);

return response;
}

Future<http.Response> fetchDataAndUpdateCookie(String url) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
final cookie = prefs.getString('cookie');

final headers = {
'Content-Type': 'application/json',
if (cookie != null) 'Cookie': cookie,
};

final response = await http.get(
Uri.parse(url),
headers: headers,
);

// Check if the server returned an updated cookie
final newCookie = response.headers['set-cookie'];
if (newCookie != null && newCookie != cookie) {
await prefs.setString('cookie', newCookie); // Update stored cookie
}

return response;
}

Future<void> logout() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.remove('cookie'); // Clear the saved cookie
}


void main() async {
// Example URLs and credentials
final loginUrl = 'https://api.example.com/login';
final fetchDataUrl = 'https://api.example.com/protected-data';
final credentials = {"username": "user", "password": "pass"};

// Login
bool loggedIn = await login(loginUrl, credentials);
if (loggedIn) {
print("Login successful!");

// Fetch data after login
final response = await fetchDataAndUpdateCookie(fetchDataUrl);
if (response.statusCode == 200) {
print("Data fetched successfully: ${response.body}");
} else {
print("Failed to fetch data: ${response.statusCode}");
}

// Logout
await logout();
print("Logged out successfully");
} else {
print("Login failed");
}
}


This is just example,if you dont know how to code use AI,nothing personal:)
 
Yes, it's possible to handle cookies in Flutter using the http package or Dio, where you can manage cookies with a CookieJar or manually save and set cookies on each request.
 
Back
Top