provider는 ui에 영향을 미치는 data, 즉 state를 핸들링하는 특정한 방법을 강요하지 않음
flutter bloc, flutter redux는 dependency injection 방법 외에 state를 다루는 특정한 방법을 제시하고 개발자가 그 방법을 따를 것을 제안함.
provider는 state를 핸들링할 수 있는 수단을 제공할 , state를 어떻게 핸들링하라는 방법론을 제공하지 않음.
비즈니스 로직을 ui와 분리했다 = BLOC (Business LOgic Component)
Provider({
Key? key,
required Create<T> create, // 유일한 required 속성
Dispose<T>? dispose,
bool? Lazy,
TransittionBuilder? builder,
Widget? child
})
create 프로퍼티에서 위젯이 필요로하는 클래스의 인스턴스를 만듦
create에 전달된 함수가 리턴하는 오브젝트를 provider 하위 위젯들은 접근할 수 있음
provider에는 of라는 static 함수 있음
이 of함수에 찾고자하는 인스턴스의 타입을 줘야함
Provider.of<Dog>(context)
Dog 클래스의 인스턴스를 제공
Dog이라는 타입을 브라켓 안에 표시 , provider가 위젯트리를 타고 올라가면서 인스턴스를 찾음.
'위젯트리를 타고 올라가면서 Dog타입의 인스턴스를 찾으면 나에게 달라는 것'
같은 타입의 인스턴스가 위젯트리 상에 두개가 있다면?
프로바이더는 위젯트리 상에서 나에게 제일 가까운 것을 줌,
더 먼데 있는 건 프로바이더를 통해 액세스 할 수 없음
A class that can be extended or mixed in that provides a change notification API using VoidCallback for notification
플러터 위젯들은 changeNotifier를 extend하거나 ChangeNotifier를 mixin한 오브젝트 인스턴스를 리슨할 수 있음
Provider.of<T>(context)
를 통해 타입의 ChangeNotifier 인스턴스 변화를 리슨해서 변화가 있으면 ui를 리빌드할 수 있고Provider.of<T>(context, listen: false)
를 통해 ChangeNotifier의 인스턴스를 액세스만 하고 변화를 리슨하지 않음onPressed: () => Provider.of<Dog>(context, listen: false).grow(),
onPressed: () => context.read<Dog>().grow(),
Provider.of<Dog>(context, listen: false).name,
context.watch<Dog>().name,
Provider.of<Dog>(context, listen: false).breed,
context.select<Dog, String>((Dog dog) => dog.breed)
참고자료
https://www.youtube.com/watch?v=-3iD7f3e_SU&t=295s
https://www.youtube.com/watch?v=de6tAJS2ZG0&t=356s
https://engineering.linecorp.com/ko/blog/flutter-architecture-getx-bloc-provider