Last active
September 1, 2022 06:44
-
-
Save supernovel/905cb21cafb4f3ecd5f99d3126100409 to your computer and use it in GitHub Desktop.
riverpod example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'package:flutter_riverpod/flutter_riverpod.dart'; | |
const Color darkBlue = Color.fromARGB(255, 18, 32, 47); | |
void main() { | |
// rivderpod 스코프 정의 | |
runApp(ProviderScope(child: MyApp())); | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
theme: ThemeData.dark().copyWith( | |
scaffoldBackgroundColor: darkBlue, | |
), | |
debugShowCheckedModeBanner: false, | |
home: Scaffold( | |
body: Center( | |
child: CounterView(), | |
), | |
), | |
); | |
} | |
} | |
// 아래와 같이 상태 및 컨트롤러를 정의하고 `ref.watch` API를 통해 여러 뷰에서 사용 가능하다. | |
final countProvider = StateNotifierProvider((ref) { | |
return CountController(); | |
}); | |
class CountController extends StateNotifier<int> { | |
CountController(): super(0); | |
increase() => state++; | |
decrease() => state--; | |
} | |
class CounterView extends ConsumerWidget { | |
@override | |
Widget build(BuildContext context, ref) { | |
// 카운터 상태 변경을 위한 컨트롤러 인스턴스를 가져온다. | |
// countController 인스턴스가 업데이트 될 때 재빌드 된다. (countController의 데이터인 count 가 업데이트 될때가 아니다.) | |
final countController = ref.watch(countProvider.notifier); | |
return Column(mainAxisSize: MainAxisSize.min, children: [ | |
const CountText(), | |
const SizedBox(height: 40), | |
Row(mainAxisAlignment: MainAxisAlignment.center, children: [ | |
TextButton(child: const Text("increase"), onPressed: countController.increase), | |
const SizedBox(width: 40), | |
TextButton(child: const Text("decrease"), onPressed: countController.decrease) | |
]) | |
]); | |
} | |
} | |
class CountText extends ConsumerWidget { | |
const CountText(); | |
@override | |
Widget build(BuildContext context, ref) { | |
// watch로 정의 시 해당 count 값이 변경 될 때 마다 다시 렌더링하도록 호출 된다. (변경사항 구독) | |
// - 어떤 식으로 처리되는 지 궁금하다면 ConsumerStatefulElement 및 StateNotifer 구현체를 참고. | |
final count = ref.watch(countProvider); | |
return Text("$count", style: const TextStyle(fontSize: 30)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment