Skip to content

Instantly share code, notes, and snippets.

@TimWhiting
Last active August 16, 2022 01:11
Show Gist options
  • Save TimWhiting/b5b6826f089d80c9b1770ec4efe4267e to your computer and use it in GitHub Desktop.
Save TimWhiting/b5b6826f089d80c9b1770ec4efe4267e to your computer and use it in GitHub Desktop.
scoped_providers
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'dart:math';
const Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(ProviderScope(child: MyApp()));
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: darkBlue,
),
debugShowCheckedModeBanner: false,
initialRoute: '/home0',
routes: {
'/home0': (context) =>
ProviderScope(overrides: [meProvider], child: HomePage()),
'/home1': (context) =>
ProviderScope(overrides: [meProvider], child: HomePage()),
'/home2': (context) =>
ProviderScope(overrides: [meProvider], child: HomePage())
});
}
}
class HomePage extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
return Column(children: [
Text(
'Hello, World! ${ref.watch(meProvider)}',
style: Theme.of(context).textTheme.headline4,
),
ElevatedButton(
child: const Text('Switch Page'),
onPressed: () {
Navigator.of(context)
.pushReplacementNamed('/home${ref.read(meProvider)}');
},
)
]);
}
}
final meProvider = Provider.autoDispose<int>((ref) {
final index = Random().nextInt(3);
ref.onDispose(() {
print('Disposing $index');
});
return index;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment