Skip to content

Instantly share code, notes, and snippets.

@VB10
Created April 16, 2025 20:11
Show Gist options
  • Save VB10/bf9a96b9ea713a6b77d0e3f972fcd689 to your computer and use it in GitHub Desktop.
Save VB10/bf9a96b9ea713a6b77d0e3f972fcd689 to your computer and use it in GitHub Desktop.
Future extension for managing try catch operation mainly.
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);
}
}
}
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