class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
Widget build(BuildContext context) {
//materialApp을 provider로 감싸줬다.
return Provider<Dog>(create: (context)=> Dog(name:'happy',breed:'Pomeranian',age:1),
child:
MaterialApp(
title: 'Provider 02',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
)
);
}
}
//다른 위젯에서 프로바이더를 호출했다.
class BreedAndAge extends StatelessWidget {
const BreedAndAge({Key? key}) : super(key: key);
Widget build(BuildContext context) {
return Column(
children: [
Text(
'- breed: ${Provider.of<Dog>(context).breed}',
style: TextStyle(fontSize: 20.0),
),
SizedBox(height: 10.0),
Age(),
],
);
}
}
//models/dog.dart
class Dog with ChangeNotifier {
final String name;
final String breed;
int age;
Dog({
required this.name,
required this.breed,
this.age = 1,
});
void grow() {
age++;
notifyListeners();
print('age:$age');
}
}
//main.dart
//dog클래스를 불러와서 값을 초기화해준뒤 사용함.
//init과 dispose를 통해 리스너를 추가해주고 삭제함.
class _MyHomePageState extends State<MyHomePage> {
final dog = Dog(name: 'cando', breed: 'breed03');
void initState() {
super.initState();
dog.addListener(dogListener);
}
void dogListener() {
print('age listener:${dog.age}');
}
void dispose() {
dog.removeListener(dogListener);
super.dispose();
}
Provider.of<T>(context)
를 통해 필요한 데이터에 쉽게 접근하고 ui를 리빌드함.//models/dog.dart
class Dog with ChangeNotifier {
final String name;
final String breed;
int age;
Dog({
required this.name,
required this.breed,
this.age = 1,
});
void grow() {
age++;
notifyListeners();
}
}
//main.dart
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
Widget build(BuildContext context) {
return ChangeNotifierProvider<Dog>(
create: (context)=> Dog(name:'hey',breed:'mumI'),
//child하위의 widget은 모두 provider에 접근 가능함
child: MaterialApp(
title: 'Provider 04',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
),
);
}
}
class BreedAndAge extends StatelessWidget {
const BreedAndAge({Key? key }) : super(key: key);
Widget build(BuildContext context) {
return Column(
children: [
//이런식으로 접근 할 수 있음!!
//리슨 설정도 가능함
Text(
'- breed: ${Provider.of<Dog>(context,listen:false).breed}',
style: TextStyle(fontSize: 20.0),
),
SizedBox(height: 10.0),
Age(),
],
);
}
}
context.read<T>()
ElevatedButton(
//context.read<Dog>: Provider.of<Dog>(context,listen:false)
onPressed: () => context.read<Dog>().grow(),
child: Text(
'Grow',
style: TextStyle(fontSize: 20.0),
),
),
context.watch<T>()
Text(
//Provider.of<Dog>(context).name
'- name: ${context.watch<Dog>().name}',
style: TextStyle(fontSize: 20.0),
),
context.select<T,R>(R selector(T vlaue))
Text(
// context.select<클래스,반환형> :Provider.of<Dog>(context)
'- breed: ${context.select<Dog,String>((Dog dog)=> dog.breed)}',
style: TextStyle(fontSize: 20.0),
),
요 강의를 듣고 정리한 내용입니다 :)