fix: velocidade da navegação e webview clean code

This commit is contained in:
J. A. Messias 2024-11-06 15:10:50 -03:00
parent efb79d2ed8
commit 5d5251a89c
5 changed files with 156 additions and 257 deletions

View File

@ -40,19 +40,9 @@ class _MenuButtonWidgetState extends State<MenuButtonWidget> {
onTap: _isProcessing onTap: _isProcessing
? null ? null
: () async { : () async {
setState(() { setState(() { _isProcessing = true; });
_isProcessing = true;
});
await LocalizationService.processLocals(context).then((value) async {
if (value) {
await widget.action.call(); await widget.action.call();
} else { setState(() { _isProcessing = false; });
DialogUnavailable.unavailableCredentials(context);
}
});
setState(() {
_isProcessing = false;
});
}, },
child: Padding( child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 0, vertical: 0), padding: const EdgeInsets.symmetric(horizontal: 0, vertical: 0),

View File

@ -40,19 +40,9 @@ class _MenuCardItemState extends State<MenuCardItem> {
onTap: _isProcessing onTap: _isProcessing
? null ? null
: () async { : () async {
setState(() { setState(() { _isProcessing = true; });
_isProcessing = true;
});
await LocalizationService.processLocals(context).then((value) async {
if (value) {
await widget.action.call(); await widget.action.call();
} else { setState(() { _isProcessing = false; });
DialogUnavailable.unavailableCredentials(context);
}
});
setState(() {
_isProcessing = false;
});
}, },
child: Card( child: Card(
elevation: 0, elevation: 0,

View File

@ -23,20 +23,14 @@ class _FastPassPageWidgetState extends State<FastPassPageWidget> {
late InAppWebViewController _controllerIOS; late InAppWebViewController _controllerIOS;
Future<Map<String, String>> initVariables() async { Future<Map<String, String>> initVariables() async {
final email = (await StorageHelper().get(hub.SecureStorageKey.email.value, hub.Storage.SecureStorage)) ?? ''; final email = await StorageHelper().get(hub.SecureStorageKey.email.value, hub.Storage.SecureStorage) ?? '';
final name = final name = await StorageHelper().get(hub.SQLiteStorageKey.userName.value, hub.Storage.SQLiteStorage) ?? '';
(await StorageHelper().get(hub.SQLiteStorageKey.userName.value, hub.Storage.SQLiteStorage)) ?? ''; final devUUID = await StorageHelper().get(hub.SQLiteStorageKey.devUUID.value, hub.Storage.SQLiteStorage) ?? '';
final devUUID = final userUUID = await StorageHelper().get(hub.SQLiteStorageKey.userUUID.value, hub.Storage.SQLiteStorage) ?? '';
(await StorageHelper().get(hub.SQLiteStorageKey.devUUID.value, hub.Storage.SQLiteStorage)) ?? ''; final cliUUID = await StorageHelper().get(hub.SQLiteStorageKey.clientUUID.value, hub.Storage.SQLiteStorage) ?? '';
final userUUID =
(await StorageHelper().get(hub.SQLiteStorageKey.userUUID.value, hub.Storage.SQLiteStorage)) ?? '';
final cliUUID =
(await StorageHelper().get(hub.SQLiteStorageKey.clientUUID.value, hub.Storage.SQLiteStorage)) ?? '';
const createdAt = '0000-00-00 00:00:00'; const createdAt = '0000-00-00 00:00:00';
final url = 'https://hub.freaccess.com.br/hub/fast-pass/$cliUUID'; final url = 'https://hub.freaccess.com.br/hub/fast-pass/$cliUUID';
final freUserData = final freUserData = "{\"name\": \"$name\", \"email\": \"$email\",\"dev_id\": \"$devUUID\",\"created_at\":\"$createdAt\",\"updated_at\": \"0000-00-00 00:00:00\",\"status\": \"A\" }";
"{\"name\": \"$name\", \"email\": \"$email\",\"dev_id\": \"$devUUID\",\"created_at\":\"$createdAt\",\"updated_at\": \"0000-00-00 00:00:00\",\"status\": \"A\" }";
return { return {
'url': url, 'url': url,
'name': name, 'name': name,
@ -57,38 +51,46 @@ class _FastPassPageWidgetState extends State<FastPassPageWidget> {
future: initVariables(), future: initVariables(),
builder: (context, snapshot) { builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) { if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator()); return const Center(child: CircularProgressIndicator());
} else if (snapshot.hasError || snapshot.hasData == false || snapshot.data!.isEmpty) { } else if (snapshot.hasError || !snapshot.hasData || snapshot.data!.isEmpty) {
return Center( return Center(child: Text(FFLocalizations.of(context).getVariableText(enText: 'Unexpected error', ptText: 'Erro inesperado')));
child: Text(FFLocalizations.of(context) } else {
.getVariableText(enText: 'Unexpected error', ptText: 'Erro inesperado')));
} else if (snapshot.hasData) {
final data = snapshot.data!; final data = snapshot.data!;
final url = data['url']!; final url = data['url']!;
final userUUID = data['userUUID']!; final userUUID = data['userUUID']!;
final freUserData = data['freUserData']!; final freUserData = data['freUserData']!;
return Platform.isIOS return Platform.isIOS
? InAppWebView( ? _buildIOSWebView(url, userUUID, freUserData)
: _buildAndroidWebView(url, userUUID, freUserData);
}
},
),
),
);
}
Widget _buildIOSWebView(String url, String userUUID, String freUserData) {
return InAppWebView(
initialUrlRequest: URLRequest(url: WebUri(url)), initialUrlRequest: URLRequest(url: WebUri(url)),
onLoadStart: (controller, url) {},
initialSettings: InAppWebViewSettings( initialSettings: InAppWebViewSettings(
allowsBackForwardNavigationGestures: true, allowsBackForwardNavigationGestures: true,
javaScriptEnabled: true, javaScriptEnabled: true,
), ),
onWebViewCreated: (controller) async => _controllerIOS = controller, onWebViewCreated: (controller) async => _controllerIOS = controller,
onLoadStop: (controller, url) async { onLoadStop: (controller, url) async {
await controller.evaluateJavascript( await controller.evaluateJavascript(source: "window.localStorage.setItem('fre-token', '\"$userUUID\"')");
source: "window.localStorage.setItem('fre-token', '\"$userUUID\"')"); await controller.evaluateJavascript(source: "window.localStorage.setItem('fre-user-data', '$freUserData')");
await controller.evaluateJavascript( await controller.evaluateJavascript(source: "window.localStorage.setItem('enableBackButton', 'true')");
source: "window.localStorage.setItem('fre-user-data', '$freUserData')");
await controller.evaluateJavascript(
source: "window.localStorage.setItem('enableBackButton', 'true')");
}, },
onUpdateVisitedHistory: (controller, uri, isVisited) { onUpdateVisitedHistory: (controller, uri, isVisited) {
if (uri.toString().contains('/hub/home')) context.pop(); if (uri.toString().contains('/hub/home')) context.pop();
}, },
) );
: WebViewWidget( }
Widget _buildAndroidWebView(String url, String userUUID, String freUserData) {
return WebViewWidget(
controller: _controllerAndroid = WebViewController() controller: _controllerAndroid = WebViewController()
..clearCache() ..clearCache()
..clearLocalStorage() ..clearLocalStorage()
@ -96,7 +98,6 @@ class _FastPassPageWidgetState extends State<FastPassPageWidget> {
..setBackgroundColor(const Color(0x00000000)) ..setBackgroundColor(const Color(0x00000000))
..setNavigationDelegate( ..setNavigationDelegate(
NavigationDelegate( NavigationDelegate(
onProgress: (int progress) {},
onPageStarted: (String url) { onPageStarted: (String url) {
final String token = "localStorage.setItem('fre-token', '\"$userUUID\"');"; final String token = "localStorage.setItem('fre-token', '\"$userUUID\"');";
final String data = "localStorage.setItem('fre-user-data', '$freUserData');"; final String data = "localStorage.setItem('fre-user-data', '$freUserData');";
@ -107,8 +108,7 @@ class _FastPassPageWidgetState extends State<FastPassPageWidget> {
_controllerAndroid.runJavaScript(backNavigation); _controllerAndroid.runJavaScript(backNavigation);
}, },
onPageFinished: (String url) { onPageFinished: (String url) {
bool isDarkMode = bool isDarkMode = SchedulerBinding.instance.platformDispatcher.platformBrightness == Brightness.dark;
SchedulerBinding.instance.platformDispatcher.platformBrightness == Brightness.dark;
if (isDarkMode) { if (isDarkMode) {
_controllerAndroid.runJavaScript(WebviewUtil.jsEnableDarkMode); _controllerAndroid.runJavaScript(WebviewUtil.jsEnableDarkMode);
@ -125,16 +125,10 @@ class _FastPassPageWidgetState extends State<FastPassPageWidget> {
}, },
onUrlChange: (url) { onUrlChange: (url) {
if (url.url.toString().contains('/hub/home')) context.pop(); if (url.url.toString().contains('/hub/home')) context.pop();
}), },
),
) )
..loadRequest(Uri.parse(url)), ..loadRequest(Uri.parse(url)),
); );
} else {
return const Center(child: Text('Unexpected error'));
}
},
),
),
);
} }
} }

View File

@ -22,22 +22,14 @@ class _ReservationPageWidgetState extends State<ReservationPageWidget> {
late WebViewController _controllerAll; late WebViewController _controllerAll;
Future<Map<String, String>> initVariables() async { Future<Map<String, String>> initVariables() async {
final email = (await StorageHelper().get(hub.SecureStorageKey.email.value, hub.Storage.SecureStorage)) ?? ''; final email = await StorageHelper().get(hub.SecureStorageKey.email.value, hub.Storage.SecureStorage) ?? '';
final name = final name = await StorageHelper().get(hub.SQLiteStorageKey.userName.value, hub.Storage.SQLiteStorage) ?? '';
(await StorageHelper().get(hub.SQLiteStorageKey.userName.value, hub.Storage.SQLiteStorage)) ?? ''; final devUUID = await StorageHelper().get(hub.SQLiteStorageKey.devUUID.value, hub.Storage.SQLiteStorage) ?? '';
final devUUID = final userUUID = await StorageHelper().get(hub.SQLiteStorageKey.userUUID.value, hub.Storage.SQLiteStorage) ?? '';
(await StorageHelper().get(hub.SQLiteStorageKey.devUUID.value, hub.Storage.SQLiteStorage)) ?? ''; final clientId = await StorageHelper().get(hub.SQLiteStorageKey.clientUUID.value, hub.Storage.SQLiteStorage) ?? '';
final userUUID =
(await StorageHelper().get(hub.SQLiteStorageKey.userUUID.value, hub.Storage.SQLiteStorage)) ?? '';
final clientId =
(await StorageHelper().get(hub.SQLiteStorageKey.clientUUID.value, hub.Storage.SQLiteStorage)) ?? '';
const createdAt = '0000-00-00 00:00:00'; const createdAt = '0000-00-00 00:00:00';
final url = 'https://hub.freaccess.com.br/hub/reservation/$clientId'; final url = 'https://hub.freaccess.com.br/hub/reservation/$clientId';
final freUserData = "{\"name\": \"$name\", \"email\": \"$email\",\"dev_id\": \"$devUUID\",\"created_at\": \"$createdAt\",\"updated_at\": \"0000-00-00 00:00:00\",\"status\": \"A\" }";
final freUserData =
"{\"name\": \"$name\", \"email\": \"$email\",\"dev_id\": \"$devUUID\",\"created_at\": \"0000-00-00 00:00:00\",\"updated_at\": \"0000-00-00 00:00:00\",\"status\": \"A\" }";
return { return {
'url': url, 'url': url,
'name': name, 'name': name,
@ -59,18 +51,25 @@ class _ReservationPageWidgetState extends State<ReservationPageWidget> {
builder: (context, snapshot) { builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) { if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator()); return const Center(child: CircularProgressIndicator());
} else if (snapshot.hasError || snapshot.hasData == false || snapshot.data!.isEmpty) { } else if (snapshot.hasError || !snapshot.hasData || snapshot.data!.isEmpty) {
return Center( return Center(child: Text(FFLocalizations.of(context).getVariableText(enText: 'Unexpected error', ptText: 'Erro inesperado')));
child: Text(FFLocalizations.of(context) } else {
.getVariableText(enText: 'Unexpected error', ptText: 'Erro inesperado')));
} else if (snapshot.hasData) {
final data = snapshot.data!; final data = snapshot.data!;
final url = data['url']!; final url = data['url']!;
final userUUID = data['userUUID']!; final userUUID = data['userUUID']!;
final freUserData = data['freUserData']!; final freUserData = data['freUserData']!;
return Platform.isIOS return Platform.isIOS
? InAppWebView( ? _buildIOSWebView(url, userUUID, freUserData)
: _buildAndroidWebView(url, userUUID, freUserData);
}
},
),
),
);
}
Widget _buildIOSWebView(String url, String userUUID, String freUserData) {
return InAppWebView(
initialUrlRequest: URLRequest(url: WebUri(url)), initialUrlRequest: URLRequest(url: WebUri(url)),
initialSettings: InAppWebViewSettings( initialSettings: InAppWebViewSettings(
allowsBackForwardNavigationGestures: true, allowsBackForwardNavigationGestures: true,
@ -78,20 +77,18 @@ class _ReservationPageWidgetState extends State<ReservationPageWidget> {
), ),
onWebViewCreated: (controller) async {}, onWebViewCreated: (controller) async {},
onLoadStop: (controller, url) async { onLoadStop: (controller, url) async {
await controller.evaluateJavascript( await controller.evaluateJavascript(source: "window.localStorage.setItem('fre-token', '\"$userUUID\"')");
source: "window.localStorage.setItem('fre-token', '\"$userUUID\"')"); await controller.evaluateJavascript(source: "window.localStorage.setItem('fre-user-data', '$freUserData')");
await controller.evaluateJavascript( await controller.evaluateJavascript(source: "window.localStorage.setItem('enableBackButton', 'true')");
source: "window.localStorage.setItem('fre-user-data', '$freUserData')");
await controller.evaluateJavascript(
source: "window.localStorage.setItem('enableBackButton', 'true')");
}, },
onUpdateVisitedHistory: (controller, uri, isVisited) { onUpdateVisitedHistory: (controller, uri, isVisited) {
if (uri.toString().contains('/hub/home')) { if (uri.toString().contains('/hub/home')) context.pop();
context.pop();
}
}, },
) );
: WebViewWidget( }
Widget _buildAndroidWebView(String url, String userUUID, String freUserData) {
return WebViewWidget(
controller: _controllerAll = WebViewController() controller: _controllerAll = WebViewController()
..clearCache() ..clearCache()
..clearLocalStorage() ..clearLocalStorage()
@ -99,7 +96,6 @@ class _ReservationPageWidgetState extends State<ReservationPageWidget> {
..setBackgroundColor(const Color(0x00000000)) ..setBackgroundColor(const Color(0x00000000))
..setNavigationDelegate( ..setNavigationDelegate(
NavigationDelegate( NavigationDelegate(
onProgress: (int progress) {},
onPageStarted: (String url) { onPageStarted: (String url) {
final String token = "localStorage.setItem('fre-token', '\"$userUUID\"');"; final String token = "localStorage.setItem('fre-token', '\"$userUUID\"');";
final String data = "localStorage.setItem('fre-user-data', '$freUserData');"; final String data = "localStorage.setItem('fre-user-data', '$freUserData');";
@ -110,8 +106,7 @@ class _ReservationPageWidgetState extends State<ReservationPageWidget> {
_controllerAll.runJavaScript(backNavigation); _controllerAll.runJavaScript(backNavigation);
}, },
onPageFinished: (String url) { onPageFinished: (String url) {
bool isDarkMode = bool isDarkMode = SchedulerBinding.instance.platformDispatcher.platformBrightness == Brightness.dark;
SchedulerBinding.instance.platformDispatcher.platformBrightness == Brightness.dark;
if (isDarkMode) { if (isDarkMode) {
_controllerAll.runJavaScript(WebviewUtil.jsEnableDarkMode); _controllerAll.runJavaScript(WebviewUtil.jsEnableDarkMode);
@ -127,19 +122,11 @@ class _ReservationPageWidgetState extends State<ReservationPageWidget> {
return NavigationDecision.prevent; return NavigationDecision.prevent;
}, },
onUrlChange: (url) { onUrlChange: (url) {
if (url.url.toString().contains('/hub/home')) { if (url.url.toString().contains('/hub/home')) context.pop();
context.pop(); },
} ),
}),
) )
..loadRequest(Uri.parse(url)), ..loadRequest(Uri.parse(url)),
); );
} else {
return const Center(child: Text('Unexpected error'));
}
},
),
),
);
} }
} }

View File

@ -1,62 +0,0 @@
// import 'dart:developer';
// import 'package:f_r_e_hub/components/templates_components/card_item_template_component/card_item_template_component_widget.dart';
// import 'package:f_r_e_hub/flutter_flow/flutter_flow_theme.dart';
// import 'package:flutter/material.dart';
// class TestPage extends StatelessWidget {
// const TestPage({Key? key}) : super(key: key);
// @override
// Widget build(BuildContext context) {
// // Exemplo de dados para os HashMaps
// final Map<String, String> labelsHashMap = {
// 'Nome:': 'Gabriel da Silva',
// 'Entrada:': '08:00 AM 01/01/2022',
// 'Saída:': '17:00 PM 01/01/2022',
// };
// // Ajuste para o novo tipo esperado pelo componente
// final Map<String, Color> statusHashMap = {
// 'Ativo': FlutterFlowTheme.of(context).success,
// };
// // função set statusHashMap que recebe um String status faz um switch case e retorna um Map<String, Color>
// Map<String, Color> getStatusHashMap(String status) {
// switch (status) {
// case 'Ativo':
// return {'Ativo': FlutterFlowTheme.of(context).success};
// case 'Inativo':
// return {'Inativo': FlutterFlowTheme.of(context).error};
// default:
// return {'Desconhecido': FlutterFlowTheme.of(context).primaryColor};
// }
// }
// // Ajuste para passar os valores corretos para a URL da imagem
// final Map<String, String> imageKeyValue = {
// 'key': 'docID',
// 'value': 'imageType',
// };
// return Scaffold(
// appBar: AppBar(
// title: const Text('Test Page'),
// ),
// body: Center(
// child: ListView.builder(
// itemCount: 10,
// itemBuilder: (context, index) {
// return CardItemTemplateComponentWidget(
// labelsHashMap: labelsHashMap,
// statusHashMap: statusHashMap,
// imageHashMap: imageKeyValue,
// onTapCardItemAction: () async {
// // Ação ao tocar no card
// },
// );
// }),
// ),
// );
// }
// }