Skip to content

Instantly share code, notes, and snippets.

@sgruhier
Created May 18, 2024 15:02
Show Gist options
  • Save sgruhier/08f336a9d151eeb15f238b0f08a1b5c7 to your computer and use it in GitHub Desktop.
Save sgruhier/08f336a9d151eeb15f238b0f08a1b5c7 to your computer and use it in GitHub Desktop.
Riverpod - FutureProvider example
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
// Define the FutureProvider for fetching data
final dataProvider = FutureProvider<String>((ref) async {
await Future.delayed(Duration(seconds: 2)); // Simulate network delay
return 'Hello, World!';
});
void main() {
runApp(
ProviderScope(
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DataPage(),
);
}
}
class DataPage extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final asyncValue = ref.watch(dataProvider);
return Scaffold(
appBar: AppBar(title: Text('FutureProvider Example')),
body: Center(
child: asyncValue.when(
data: (data) => Text('Data: $data', style: TextStyle(fontSize: 24)),
loading: () => CircularProgressIndicator(),
error: (error, stack) => Text('Error: $error'),
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment