Created
April 16, 2025 20:11
-
-
Save VB10/bf9a96b9ea713a6b77d0e3f972fcd689 to your computer and use it in GitHub Desktop.
Future extension for managing try catch operation mainly.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension TestSafety<T> on Future<T> { | |
/// This method is used to safely run a future and return a nullable value. | |
/// If the future throws an error, it will be caught and logged. | |
Future<T?> safe() async { | |
try { | |
return await this; | |
} catch (e) { | |
CustomLogger.showError(e); | |
return null; | |
} | |
} | |
/// This method is used to safely run a future and return a void value. | |
/// If the future throws an error, it will be caught and logged. | |
Future<void> safeVoid() async { | |
try { | |
await this; | |
} catch (e) { | |
CustomLogger.showError(e); | |
} | |
} | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class HomeView extends StatelessWidget { | |
const HomeView({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
return FloatingActionButton( | |
onPressed: () async { | |
await fetchUser().safe(); | |
}, | |
child: const Icon(Icons.add), | |
); | |
} | |
Future<void> fetchUser() { | |
return Future.delayed(const Duration(seconds: 2)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment