Created with <3 with dartpad.dev.
Created
July 4, 2023 07:49
-
-
Save qisantanu/4ef2cc1902ce8bbb593597fb4e8a786a to your computer and use it in GitHub Desktop.
Riverpod sample
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
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file | |
// for details. All rights reserved. Use of this source code is governed by a | |
// BSD-style license that can be found in the LICENSE file. | |
import 'package:flutter/material.dart'; | |
import 'package:flutter_riverpod/flutter_riverpod.dart'; | |
// This is a reimplementation of the default Flutter application | |
// using riverpod. | |
void main() { | |
runApp( | |
// Adding ProviderScope enables Riverpod for the entire project | |
const ProviderScope(child: MyApp()), | |
); | |
} | |
class CounterNotifier extends ChangeNotifier { | |
int _cnt = 0; | |
int get cnt => _cnt; | |
void incrementCounter() { | |
_cnt = _cnt + 1; | |
notifyListeners(); | |
} | |
} | |
/// Providers are declared globally and specify how to create a state | |
final counterProvider = ChangeNotifierProvider((ref) => CounterNotifier()); | |
class MyApp extends StatelessWidget { | |
const MyApp({Key? key}) : super(key: key); | |
@override | |
Widget build(BuildContext context) { | |
return const MaterialApp( | |
home: MyHomePage(), | |
); | |
} | |
} | |
class MyHomePage extends ConsumerWidget { | |
const MyHomePage({Key? key}) : super(key: key); | |
void _incrCounter(ref) { | |
ref.read(counterProvider).incrementCounter(); | |
} | |
@override | |
Widget build(BuildContext context, WidgetRef ref) { | |
return Scaffold( | |
appBar: AppBar( | |
title: const Text('Riverpod example'), | |
), | |
body: Center( | |
child: Column( | |
mainAxisSize: MainAxisSize.min, | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: <Widget>[ | |
const Text('You have pushed the button this many times:'), | |
Consumer( | |
builder: (context, ref, _) { | |
final counterNotifier = ref.watch(counterProvider); | |
final count = counterNotifier.cnt; | |
return Text( | |
'$count', | |
key: const Key('counterState'), | |
style: Theme.of(context).textTheme.headlineMedium, | |
); | |
}, | |
), | |
], | |
), | |
), | |
floatingActionButton: FloatingActionButton( | |
key: const Key('increment_floatingActionButton'), | |
// The read method is a utility to read a provider without listening to it | |
onPressed: () => _incrCounter(ref), | |
tooltip: 'Increment', | |
child: const Icon(Icons.add), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment