62 lines
1.3 KiB
Dart
62 lines
1.3 KiB
Dart
import 'package:flutter/material.dart';
|
|
import 'package:provider/provider.dart';
|
|
|
|
class Counter extends ChangeNotifier {
|
|
int _count = 0;
|
|
int get count => _count;
|
|
|
|
void increment() {
|
|
_count++;
|
|
notifyListeners();
|
|
}
|
|
}
|
|
|
|
class ChangeNotifierPage extends StatelessWidget {
|
|
const ChangeNotifierPage({super.key});
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return ChangeNotifierProvider(
|
|
create: (_) => Counter(),
|
|
child: Scaffold(
|
|
appBar: AppBar(
|
|
title: const Text('ChangeNotifier Provider'),
|
|
),
|
|
body: Center(
|
|
child: Column(
|
|
mainAxisAlignment: MainAxisAlignment.center,
|
|
children: [
|
|
const CountDisplay(),
|
|
const CounterIncrement(),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
class CountDisplay extends StatelessWidget {
|
|
const CountDisplay({super.key});
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return Text(
|
|
'Count: ${context.watch<Counter>().count}',
|
|
style: Theme.of(context).textTheme.headlineMedium,
|
|
);
|
|
}
|
|
}
|
|
|
|
class CounterIncrement extends StatelessWidget {
|
|
const CounterIncrement({super.key});
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return ElevatedButton(
|
|
onPressed: () => context.read<Counter>().increment(),
|
|
child: const Text('Increment'),
|
|
);
|
|
}
|
|
}
|