Created
September 3, 2023 22:30
-
-
Save DaisukeNagata/5f062de864572c56d2b96aea18e0f5de to your computer and use it in GitHub Desktop.
refresh data by riverbod
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 'dart:math'; | |
import 'package:flutter/material.dart'; | |
import 'package:flutter_riverpod/flutter_riverpod.dart'; | |
void main() { | |
runApp( | |
const ProviderScope(child: MyApp()), | |
); | |
} | |
final dataProvider = FutureProvider<String>((ref) async { | |
await Future.delayed(const Duration(milliseconds: 100)); | |
return "Initial Data${Random().nextInt(1000)}"; | |
}); | |
class MyApp extends ConsumerWidget { | |
const MyApp({super.key}); | |
@override | |
Widget build(BuildContext context, WidgetRef ref) { | |
return MaterialApp( | |
title: 'Riverpod Refresh Example', | |
theme: ThemeData(primarySwatch: Colors.blue), | |
home: const MyHomePage(), | |
); | |
} | |
} | |
class MyHomePage extends ConsumerWidget { | |
const MyHomePage({super.key}); | |
@override | |
Widget build(BuildContext context, WidgetRef ref) { | |
return Scaffold( | |
appBar: AppBar(title: const Text('Riverpod Refresh Example')), | |
body: Center( | |
child: _reloadText(ref), | |
), | |
floatingActionButton: Column( | |
mainAxisAlignment: MainAxisAlignment.end, | |
children: [ | |
FloatingActionButton( | |
onPressed: () { | |
showDialog( | |
context: context, | |
builder: (dialogContext) { | |
return AlertDialog( | |
title: const Text("Data Alert"), | |
content: Consumer( | |
builder: (BuildContext context, WidgetRef ref, child) { | |
return _reloadText(ref); | |
}, | |
), | |
actions: [ | |
TextButton( | |
onPressed: () async { | |
Future(() => ref.refresh(dataProvider)); | |
}, | |
child: const Text("Refresh Data"), | |
), | |
TextButton( | |
onPressed: () { | |
Navigator.of(dialogContext).pop(); | |
}, | |
child: const Text("Close"), | |
), | |
], | |
); | |
}, | |
); | |
}, | |
child: const Icon(Icons.info), | |
), | |
FloatingActionButton( | |
onPressed: () { | |
Future(() => ref.refresh(dataProvider)); | |
}, | |
child: const Icon(Icons.refresh), | |
), | |
], | |
), | |
); | |
} | |
Widget _reloadText(WidgetRef ref) { | |
return ref.watch(dataProvider).when( | |
data: (data) => Text(data), | |
loading: () => const 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
2023-09-04.7.30.51.mov