Created
June 4, 2024 19:08
-
-
Save chillbrodev/3cc4e8ddfa6b4bb1456a8b95d44db76d to your computer and use it in GitHub Desktop.
Flutter Counter With Riverpod
This file contains hidden or 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 2019 the Dart project authors. 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'; | |
void main() { | |
final providerScope = ProviderScope( | |
overrides: [], | |
child: const MyApp(), | |
); | |
runApp(providerScope); | |
} | |
class MyApp extends StatelessWidget { | |
const MyApp({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
debugShowCheckedModeBanner: false, | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: const MyHomePage(title: 'Flutter Demo Home Page'), | |
); | |
} | |
} | |
class MyHomePage extends ConsumerStatefulWidget { | |
final String title; | |
const MyHomePage({ | |
super.key, | |
required this.title, | |
}); | |
@override | |
ConsumerState<MyHomePage> createState() => _MyHomePageState(); | |
} | |
class _MyHomePageState extends ConsumerState<MyHomePage> { | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text(widget.title), | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: [ | |
const Text( | |
'You have pushed the button this many times:', | |
), | |
Text( | |
'${ref.watch(CounterNotifier.provider)}', | |
style: Theme.of(context).textTheme.headlineMedium, | |
), | |
], | |
), | |
), | |
floatingActionButton: FloatingActionButton( | |
onPressed: ref.read(CounterNotifier.provider.notifier).increment, | |
tooltip: 'Increment', | |
child: const Icon(Icons.add), | |
), | |
); | |
} | |
} | |
class CounterNotifier extends AutoDisposeNotifier<int> { | |
static final provider = | |
AutoDisposeNotifierProvider<CounterNotifier, int>(CounterNotifier.new); | |
@override | |
int build() => 0; | |
void increment() => state++; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment