Created
August 18, 2020 19:30
-
-
Save VB10/8c699445e6cf6eaf47875aa223df1a06 to your computer and use it in GitHub Desktop.
Future Extension Flutter
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 FutureExtension on Future { | |
Widget toBuild<T>({Widget Function(T data) onSuccess, Widget onError, dynamic data}) { | |
return FutureBuilder<T>( | |
future: this, | |
initialData: data, | |
builder: (BuildContext context, AsyncSnapshot snapshot) { | |
switch (snapshot.connectionState) { | |
case ConnectionState.waiting: | |
case ConnectionState.active: | |
return Center(child: CircularProgressIndicator()); | |
case ConnectionState.done: | |
if (snapshot.hasData) | |
return onSuccess(snapshot.data); | |
else | |
return onError ?? NotFoundLottie(); | |
break; | |
default: | |
return NotFoundLottie(); | |
} | |
}, | |
); | |
} | |
} | |
class SampleFuture extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return Future.value(5).toBuild<int>( | |
onSuccess: (data) { | |
return Text(data.toString()); | |
}, | |
onError: Text("Not Found")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment