Provider 패키지를 사용

변수를 편하게 보낼 수 있다 함.

Provider 안에 모든 변수를 다 담아놓고 공유해서 사용하는 것임.

설치

# pubspec.yml
provider: ^6.0.1

프로바이더 패키지 설치

import 'package:provider/provider.dart';

패키지 가져오기

사용

Store class 만들기

class Store1 extends ChangeNotifier {
  var name = 'john kim';
}

store 원하는 위젯에 등록하기

위 state 가져다 쓰고 싶은 애들은 ChangeNotifierProvider 로 감싸야 함.

ChangeNotifierProvider(
    create: (c) => Store1(),
    child: MaterialApp(
      theme: style.theme,
      home: MyApp()
      ),
  )

원래 MaterialApp 부분을 위젯으로 감싸서 위젯의 이름을 ChangeNotifierProvider 로 만들어줌.

cretae 함수를 사용하여 Store1을 만들면

이제 MaterialApp 자식들은 Store1에 있는 애를 사용할 수 있음.

appBar: AppBar(title: Text(context.watch<Store1>().name),),

이렇게 사용하면 됨

감격!

커스텀 위젯 별로 없으면 그냥 3step으로 쓰는게 좋음.

store 에 있는 state 변경 방법

이거 막 만지면 안됨.

그래서 막 만질수 없음. 매뉴얼을 만들어서만 쓸 수 있게 해놨음

안에서 함수 만들어서 사용해야 한다.

class Store1 extends ChangeNotifier {
  var name = 'john kim';
  changeName() {
    name = 'john park';
    notifyListeners();
  }
}

이런식으로 일단 함수를 만듬 (매뉴얼임.) notifyListeners를 써야 렌더링 다시 해줌.

정리

  1. Store를 만든다.
  2. 쓰고 싶은 위젯을 ChangeNotifierProvider로 감싼다.
  3. 쓸 때 문법을 유의해서 사용한다. context.watch (변수 갔다 씀) context.read (함수 갔다 씀)

숙제

  1. follower 숫자 보여주기.
  2. 팔로우 버튼 누르면 1명 증가
  3. 한번더 누르면 다시 1명 감소

레이아웃
 children: [
         CircleAvatar(radius: 30, backgroundColor: Colors.grey,),
         Text('팔로워 ${context.watch<Store1>().follower} 명'),
         ElevatedButton(onPressed: (){
            context.read<Store1>().setFollower();
         }, child: Text('팔로우'))
       ],

프로필 위젯에 위와 같으 코딩

Store 코딩
  var follower = 0;
  var isFollow = false;

  setFollower() {
    if(!isFollow){
      follower++;
      isFollow = !isFollow;
    }
    else{
      follower--;
      isFollow = !isFollow;
    }
    notifyListeners();
  }

Store 를 여러개 만드는 경우

class Store2 extends ChangeNotifier {
  var name = 'john kim';
}

이런식으로 Store를 만들었다고 하자.

 runApp(MultiProvider(
    providers: [
      ChangeNotifierProvider(create: (c) => Store1()),
      ChangeNotifierProvider(create: (c) => Store2()),
    ],
    child: MaterialApp(
      theme: style.theme,
      home: MyApp()
      ),
  )
  );

위와 같이 두개를 등록해줄 수 있다. MultiProvider 를 사용해야한다는 점이 다름.

그리고 ChangeNotifierProvider도 두개 등록해줘야함.

profile 방문 시

get 요청해서 Store에 등록해주고 싶다면?