future_widget 0.0.1
future_widget: ^0.0.1 copied to clipboard
FutureWidget — a pragmatic and clearer alternative to FutureBuilder/StreamBuilder
example/lib/main.dart
import 'package:flutter/material.dart';
import 'package:future_widget/future_widget.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(),
body: const Center(
child: ExampleWidget(),
),
),
);
}
}
int num = 0;
class ExampleWidget extends StatefulWidget {
const ExampleWidget({Key? key}) : super(key: key);
@override
ExampleWidgetState createState() => ExampleWidgetState();
}
class ExampleWidgetState extends State<ExampleWidget> {
RefreshableFuture<int> rf = RefreshableFuture<int>(
myFuture(false),
RefreshType.nonPriorityDebounced,
);
@override
void initState() {
super.initState();
}
static Future<int> myFuture(bool shouldThrow) async {
await Future.delayed(const Duration(seconds: 4));
if (shouldThrow) {
throw Exception("You can't pass true as a param");
}
return num++;
}
@override
Widget build(BuildContext context) {
return Column(
children: [
FutureWidget<int>(
refreshableFuture: rf,
onData: (context, data, isRefreshing, onLoading) => isRefreshing
? onLoading(context)
: Text('My data is: $data${isRefreshing ? ' (REFRESHING)' : ''}'),
onError: (context, error, stackTrace, isRefreshing, onLoading) {
return Text(
'Error was thrown: $error${isRefreshing ? ' (REFRESHING)' : ''}',
);
},
onLoading: (context) => const Text('Loading...'),
),
ElevatedButton(
onPressed: () {
setState(() {
rf = RefreshableFuture<int>(
myFuture(false),
RefreshType.priorityDebounced,
);
});
},
child: const Text('increase num'),
),
ElevatedButton(
onPressed: () {
setState(() {
rf = RefreshableFuture<int>(
myFuture(true),
RefreshType.priorityUnfiltered,
);
});
},
child: const Text('error'),
),
],
);
}
}