728x90
목표
Riverpod을 사용해 기본 예제인 Counter App을 만들어보고 Provider의 기능 및 작동 순서를 확인해본다.
실제 예제
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
// A Counter Example App Provided with RiverPod
void main() {
runApp(
/// 1. Provide the ProviderScope at the optimum poistion in order to enable
/// the approach from every single angle of the project
const ProviderScope(child: MyApp()),
);
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(debugShowCheckedModeBanner: false, home: Home());
}
}
/// Remove Debug Mode Banner on the top of the app
late final bool debugShowCheckedModeBanner;
///2. State the Provider and set the reference state
final counterProvider = StateProvider((ref) => 1);
///3. Claim the Extends using ConsumerWidget which indicates that the following
///class is a consumer
class Home extends ConsumerWidget {
@override
/// 4. Add WidgetRef ref at the build Method
Widget build(BuildContext context, WidgetRef ref) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.deepPurpleAccent,
title: const Text('Counter')),
body: Center(
/// 5. Enable the provider reading in the widet
/// 6. Watch method makes it possible to check any changes in case of
/// Rebuilding
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: Text(
"How many counts did you make?",
style: TextStyle(fontSize: 15),
),
),
SizedBox(height: 30),
Consumer(
builder: (context, ref, _) {
final count = ref.watch(counterProvider.state).state;
return Text(
'$count',
style: TextStyle(fontSize: 25),
);
},
),
],
),
),
),
floatingActionButton: Stack(
children: <Widget>[
Align(
alignment: Alignment(
Alignment.bottomRight.x, Alignment.bottomRight.y - 0.1),
child: FloatingActionButton(
/// watch Method for the formula (Addition)
backgroundColor: Colors.deepPurpleAccent,
onPressed: () => ref.watch(counterProvider.state).state++,
child: const Icon(Icons.add),
),
),
Align(
alignment: Alignment(
Alignment.bottomRight.x - 0.4, Alignment.bottomRight.y - 0.1),
child: FloatingActionButton(
/// watch Method for the formula (Abstraction)
backgroundColor: Colors.deepPurple,
onPressed: () => ref.watch(counterProvider.state).state--,
child: const Icon(Icons.remove),
),
),
Align(
alignment: Alignment(
Alignment.bottomRight.x - 0.8, Alignment.bottomRight.y - 0.1),
child: FloatingActionButton(
/// watch Method for the formual (Refresh)
backgroundColor: Colors.purple,
onPressed: () => ref.watch(counterProvider.state).state = 0,
child: const Icon(Icons.refresh),
),
),
],
),
);
}
}
실제 구동 화면
728x90
'Flutter' 카테고리의 다른 글
[플러그인] 사용하기 좋은 플러그인 7가지 소개 (0) | 2023.03.30 |
---|---|
[Practice] TodoList만들기 (0) | 2023.03.29 |
9. Optimistic Response (0) | 2023.03.16 |
8. Swagger (0) | 2023.03.16 |
7. Debounce와 Throttle (0) | 2023.03.15 |