Created
May 18, 2024 15:02
-
-
Save sgruhier/08f336a9d151eeb15f238b0f08a1b5c7 to your computer and use it in GitHub Desktop.
Riverpod - FutureProvider example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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