Skip to content

Instantly share code, notes, and snippets.

@rodydavis
Created March 12, 2023 02:55
Show Gist options
  • Save rodydavis/1ad93e0c090d17ae96c4a76a804384e8 to your computer and use it in GitHub Desktop.
Save rodydavis/1ad93e0c090d17ae96c4a76a804384e8 to your computer and use it in GitHub Desktop.
Using Riverpod for Widget generation
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'generated.g.dart';
@riverpod
class GeneratedWidget extends _$GeneratedWidget {
@override
Widget build(BuildContext context) {
return const Text('Generated widget!');
}
}
@riverpod
class StreamWidget extends _$StreamWidget {
@override
Stream<Widget> build(BuildContext context) async* {
final controller = StreamController<int>();
final timer = Timer.periodic(const Duration(seconds: 1), (timer) {
controller.add(timer.tick);
});
yield* controller.stream.map((event) => Text('Stream widget: $event'));
timer.cancel();
await controller.close();
}
}
@riverpod
class FutureWidget extends _$FutureWidget {
@override
Future<Widget> build(BuildContext context) async {
await Future.delayed(const Duration(seconds: 3));
return const Text('Future completed!');
}
}
class Example extends StatelessWidget {
const Example({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Column(
children: [
Consumer(builder: (context, ref, child) {
final generated = ref.watch(generatedWidgetProvider(context));
return generated;
}),
Consumer(builder: (context, ref, child) {
final stream = ref.watch(streamWidgetProvider(context));
return stream.when(
data: (data) => data,
error: (error, stack) => Text(error.toString()),
loading: () => const CircularProgressIndicator(),
);
}),
Consumer(builder: (context, ref, child) {
final future = ref.watch(futureWidgetProvider(context));
return future.when(
data: (data) => data,
error: (error, stack) => Text(error.toString()),
loading: () => const CircularProgressIndicator(),
);
}),
],
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment