Provider 사용 예제
전 게시글에서 provider 패키지를 pubspec.yaml 에 추가해줬다. 이제 아주아주 간단한 예제를 통해 사용해 보자!
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("provider test"),
),
body: Center(
child: Column(
children: [
const Padding(
padding: EdgeInsets.all(30.0),
child: Text(
"Count",
style: TextStyle(fontSize: 20),
),
),
Row(
children: [
Expanded(
child: Container(),
),
ElevatedButton(
onPressed: () {},
child: const Text("+"),
),
const SizedBox(
width: 10,
),
ElevatedButton(
onPressed: () {},
child: const Text("-"),
),
Expanded(
child: Container(),
),
],
)
],
),
),
);
}

import 'package:flutter/material.dart';
class ProviderEx extends ChangeNotifier {
int _count = 0;
int get count => _count;
void increase() {
_count++;
notifyListeners();
}
void decrease() {
_count--;
notifyListeners();
}
}
void main() {
runApp(MaterialApp(
home: ChangeNotifierProvider(
create: (_) => ProviderEx(),
child: const MyHomePage(),
), // 앱의 첫 페이지 또는 홈 페이지를 지정하세요.
),
);
}
@override
Widget build(BuildContext context) {
final providerEx = Provider.of<ProviderEx>(context, listen: false);
return Scaffold(
appBar: AppBar(
title: const Text("provider test"),
),
body: Center(
child: Consumer<ProviderEx>(
builder: (context, provider, child) => Column(
children: [
Padding(
padding: const EdgeInsets.all(30.0),
child: Text(
providerEx.count.toString(),
style: const TextStyle(fontSize: 20),
),
),
Row(
children: [
Expanded(
child: Container(),
),
ElevatedButton(
onPressed: () {
//증가 함수 실행
providerEx.increase();
},
child: const Text("+"),
),
const SizedBox(
width: 10,
),
ElevatedButton(
onPressed: () {
providerEx.decrease();
},
child: const Text("-"),
),
Expanded(
child: Container(),
),
],
)
],
),
),
),
);
}