Last active
May 3, 2023 18:58
-
-
Save chimon2000/f543fd97d233147ab10355cd3699afac to your computer and use it in GitHub Desktop.
Counter Notifier
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 'package:flutter/material.dart'; | |
void main() => runApp(CounterApp()); | |
class CounterApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
debugShowCheckedModeBanner: false, | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: const HomePage(title: 'Flutter Demo Home Page'), | |
); | |
} | |
} | |
class HomePage extends StatelessWidget { | |
const HomePage({ | |
Key? key, | |
required this.title, | |
}) : super(key: key); | |
final String title; | |
@override | |
Widget build(BuildContext context) { | |
return CounterScope( | |
notifier: CounterController(), | |
child: Scaffold( | |
appBar: AppBar( | |
title: Text(title), | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: const [ | |
Text( | |
'You have pushed the button this many times:', | |
), | |
CounterDisplay(), | |
], | |
), | |
), | |
floatingActionButton: const IncrementButton(), | |
), | |
); | |
} | |
} | |
class CounterDisplay extends StatelessWidget { | |
const CounterDisplay({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
return Text( | |
'${CounterScope.of(context).value}', | |
style: Theme.of(context).textTheme.headlineMedium, | |
); | |
} | |
} | |
class IncrementButton extends StatelessWidget { | |
const IncrementButton({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
return Builder( | |
builder: (context) => FloatingActionButton( | |
onPressed: CounterScope.of(context).increment, | |
tooltip: 'Increment', | |
child: const Icon(Icons.add), | |
), | |
); | |
} | |
} | |
class CounterScope extends InheritedNotifier<CounterController> { | |
const CounterScope({ | |
super.key, | |
required super.child, | |
super.notifier, | |
}); | |
static CounterController of(BuildContext context) { | |
final CounterScope? result = | |
context.dependOnInheritedWidgetOfExactType<CounterScope>(); | |
assert(result != null, 'No CounterScope found in context'); | |
assert(result!.notifier != null, 'No CounterController found in context'); | |
return result!.notifier!; | |
} | |
} | |
class CounterController extends ValueNotifier<int> { | |
CounterController([int initialValue = 0]) : super(initialValue); | |
void increment() { | |
value = value + 1; | |
} | |
void decrement() { | |
value = value - 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment