AutoDisposeStreamProvider<T> constructor
AutoDisposeStreamProvider<T> (
- Stream<
T> _createFn(- AutoDisposeStreamProviderRef<
T> ref
- AutoDisposeStreamProviderRef<
- {String? name,
- Iterable<
ProviderOrFamily> ? dependencies, - @Deprecated('Will be removed in 3.0.0') Family<
Object?> ? from, - @Deprecated('Will be removed in 3.0.0') Object? argument,
- @Deprecated('Will be removed in 3.0.0') DebugGetCreateSourceHash? debugGetCreateSourceHash}
Creates a stream and exposes its latest event.
StreamProvider is identical in behavior/usage to FutureProvider, modulo the fact that the value created is a Stream instead of a Future.
It can be used to express a value asynchronously loaded that can change over
time, such as an editable Message
coming from a web socket:
final messageProvider = StreamProvider.autoDispose<String>((ref) async* {
// Open the connection
final channel = IOWebSocketChannel.connect('ws://echo.websocket.org');
// Close the connection when the stream is destroyed
ref.onDispose(() => channel.sink.close());
// Parse the value received and emit a Message instance
await for (final value in channel.stream) {
yield value.toString();
}
});
Which the UI can then listen:
Widget build(BuildContext context, WidgetRef ref) {
AsyncValue<String> message = ref.watch(messageProvider);
return message.when(
loading: () => const CircularProgressIndicator(),
error: (err, stack) => Text('Error: $err'),
data: (message) {
return Text(message);
},
);
}
Note: When listening to web sockets, firebase, or anything that consumes resources, it is important to use StreamProvider.autoDispose instead of simply StreamProvider.
This ensures that the resources are released when no longer needed as, by default, a StreamProvider is almost never destroyed.
See also:
- Provider, a provider that synchronously creates a value
- FutureProvider, a provider that asynchronously exposes a value that can change over time.
- future, to obtain the last value emitted by a Stream.
- StreamProvider.family, to create a StreamProvider from external parameters
- StreamProvider.autoDispose, to destroy the state of a StreamProvider when no longer needed.
Implementation
AutoDisposeStreamProvider(
this._createFn, {
super.name,
super.dependencies,
@Deprecated('Will be removed in 3.0.0') super.from,
@Deprecated('Will be removed in 3.0.0') super.argument,
@Deprecated('Will be removed in 3.0.0') super.debugGetCreateSourceHash,
}) : super(
allTransitiveDependencies:
computeAllTransitiveDependencies(dependencies),
);