Hi There, I'm trying to run heartBeat call that runs every 1 min, and it will call an API, and if the result is not 200OK, it will navigate to login page. I'm currently facing the issue where I can't pass my JWT to my custom action in order to call my API, and also, I'm unable to to use the build context in order to navigate to the login page. Any idea how can I overcome this issue ? I don't want to put this logic in all my pages, since I have many pages, and few more in the future.
Thanks in advance for any help! ๐
What have you tried so far?
I want to write something like this:
// Automatic FlutterFlow imports
import '/backend/backend.dart';
import '/backend/schema/structs/index.dart';
import '/flutter_flow/flutter_flow_theme.dart';
import '/flutter_flow/flutter_flow_util.dart';
import '/custom_code/actions/index.dart'; // Imports other custom actions
import '/flutter_flow/custom_functions.dart'; // Imports custom functions
import 'package:flutter/material.dart';
// Begin custom action code
// DO NOT REMOVE OR MODIFY THE CODE ABOVE!
import 'dart:async';
import 'package:http/http.dart' as http;
Future<void> startHeartbeat(String jwt) async {
print('Start heartbeat...');
const duration = Duration(minutes: 1);
Timer.periodic(duration, (Timer t) => _sendHeartbeat(jwt));
}
Future<void> _sendHeartbeat(jwt) async {
final url =
'https://MYURL/v2/heartBeat';
try {
final response = await http.get(Uri.parse(url),
headers: <String, String>{
'Authorization': '$jwt',
});
if (response.statusCode != 200) {
// If the server did not return a 200 OK response,
// navigate to the login page
//_navigateToLoginIfNeeded(context);
print('Naviage to Login');
}
} catch (e) {
print('Error sending heartbeat: $e');
// In case of any error (e.g., no internet connection),
// navigate to the login page
print('Naviage to Login');
}
}
void _navigateToLoginIfNeeded(BuildContext context) {
// Get the current route name
final currentRouteName = ModalRoute.of(context)?.settings.name;
// Replace 'LoginPage' with the actual name of your login page in FlutterFlow
const loginPageName = 'newLogin';
// Check if the current page is not the login page
if (currentRouteName != loginPageName) {
// Navigate to the login page
context.goNamed(loginPageName);
}
}
// Set your action name, define your arguments and return parameter,
// and then add the boilerplate code using the green button on the right!
Did you check FlutterFlow's Documentation for this topic?