Skip to content

Instantly share code, notes, and snippets.

@DaisukeNagata
Created September 3, 2023 22:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DaisukeNagata/5f062de864572c56d2b96aea18e0f5de to your computer and use it in GitHub Desktop.
Save DaisukeNagata/5f062de864572c56d2b96aea18e0f5de to your computer and use it in GitHub Desktop.
refresh data by riverbod
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'),
);
}
}
@DaisukeNagata
Copy link
Author

2023-09-04.7.30.51.mov

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment