polling_builder 0.1.0
polling_builder: ^0.1.0 copied to clipboard
A Flutter widget that polls data at regular intervals and when conditions are met, similar to StreamBuilder but for polling APIs.
Polling Builder #
A Flutter widget that polls data at regular intervals and rebuilds when specified conditions are met. Think of it as a StreamBuilder
for polling APIs or any data that needs to be refreshed periodically.
Features #
- 🔄 Automatic polling at configurable intervals
- 🎯 Conditional rebuilding with
buildWhen
- 🛡️ Automatic cleanup and lifecycle management
- ❌ Built-in error handling
- 🚀 Easy to use, similar to StreamBuilder
- 📱 Works with any data type
Installation #
Add this to your package's pubspec.yaml
file:
dependencies:
polling_builder: ^0.1.0
Usage #
Basic Usage #
PollingBuilder<String>(
// Function that fetches your data
dataFetcher: () async {
// This could be any async operation, like an API call
return await myApiService.fetchData();
},
// How often to poll for new data
pollInterval: Duration(seconds: 30),
// Builder function similar to StreamBuilder
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
if (!snapshot.hasData) {
return CircularProgressIndicator();
}
return Text('Data: ${snapshot.data}');
},
)
Advanced Usage with buildWhen
#
The buildWhen
parameter allows you to control when the widget rebuilds, which is useful for optimizing performance or implementing custom comparison logic:
PollingBuilder<Map<String, dynamic>>(
dataFetcher: () async {
// Fetch weather data
return await weatherApi.getCurrentConditions();
},
pollInterval: Duration(minutes: 5),
// Only rebuild if the temperature has changed by more than 1 degree
buildWhen: (previous, current) {
if (previous == null || current == null) return true;
return (previous['temperature'] - current['temperature']).abs() > 1;
},
builder: (context, snapshot) {
// UI building logic
if (snapshot.hasData) {
return WeatherDisplay(data: snapshot.data!);
}
return LoadingIndicator();
},
)
Manual Control #
You can manually control the polling by setting autoStart: false
and accessing the state:
class _WeatherScreenState extends State<WeatherScreen> {
final _pollingKey = GlobalKey<_PollingBuilderState>();
@override
Widget build(BuildContext context) {
return Column(
children: [
PollingBuilder<WeatherData>(
key: _pollingKey,
dataFetcher: () => weatherApi.getWeather(),
pollInterval: Duration(minutes: 10),
autoStart: false, // Don't start polling automatically
builder: (context, snapshot) {
// Your UI building logic here
},
),
Row(
children: [
ElevatedButton(
onPressed: () => _pollingKey.currentState?.startPolling(),
child: Text('Start Updates'),
),
ElevatedButton(
onPressed: () => _pollingKey.currentState?.stopPolling(),
child: Text('Stop Updates'),
),
],
),
],
);
}
}
API Reference #
PollingBuilder<T>
#
Parameter | Type | Description |
---|---|---|
dataFetcher |
Future<T> Function() |
Function that fetches data asynchronously |
pollInterval |
Duration |
How often to poll for new data |
builder |
Widget Function(BuildContext, AsyncSnapshot<T>) |
Builder function that creates widgets from data |
buildWhen |
bool Function(T? previousBuiltData, T? currentData)? |
Optional function to determine when the widget should rebuild |
initialData |
T? |
Optional initial data to show before first poll completes |
autoStart |
bool |
Whether to start polling immediately (default: true) |
When to Use PollingBuilder #
- Displaying data that needs to be refreshed periodically from a server
- Building UIs that show real-time data without using WebSockets
- Creating dashboards with auto-refreshing widgets
- Implementing "pull to refresh" functionality with a base refresh interval
Lifecycle Management #
PollingBuilder
automatically handles:
- Starting polling when the widget is mounted (if
autoStart
is true) - Stopping polling when the widget is removed from the tree
- Preventing memory leaks by properly cleaning up resources
Comparison with Other Approaches #
Approach | Pros | Cons |
---|---|---|
PollingBuilder | - Simple API - Automatic lifecycle management - Conditional rebuilds |
- Not suitable for high-frequency updates |
StreamBuilder | - Real-time updates - Great for event-based data |
- More complex to set up - Requires managing Stream subscriptions |
FutureBuilder | - Simple one-time data fetch | - No automatic refreshing - Requires manual refresh triggers |
Manual Timer | - Full control over polling logic | - Requires manual cleanup - More boilerplate code |
Example #
For a complete example, check out the example directory.
Contributing #
Contributions are welcome! Please feel free to submit a Pull Request.
License #
This project is licensed under the MIT License - see the LICENSE file for details.