필드를 비공개로 유지하기
Coddy Flutter 여정의 상태 관리 섹션에 포함된 레슨. 27개 중 7번째.
온도 조절기는 26도를 넘거나 16도 미만이 되어서는 안 됩니다. warmer 메서드로 이를 확인할 수 있지만, 다른 방법으로 숫자를 바꿀 수 있는 사람이 아무도 없을 때만 가능합니다. 필드가 공개되어 있으면 어떤 코드든 thermostat.degrees = 99를 쓸 수 있습니다.
_로 시작하는 이름은 비공개입니다. 같은 파일에 있는 코드만 사용할 수 있습니다. 클래스를 별도의 파일에 넣고 필드를 비공개로 만든 다음, 외부에서 값을 읽을 수 있도록 게터를 제공하고 값을 변경할 메서드를 만드세요:
// thermostat.dart
class Thermostat {
int _degrees = 20;
int get degrees => _degrees;
void warmer() {
if (_degrees < 26) {
_degrees = _degrees + 1;
}
}
}페이지는 import 'thermostat.dart';로 파일을 가져옵니다. thermostat.degrees를 읽을 수는 있지만, thermostat.degrees++는 더 이상 컴파일되지 않습니다. 게터만 있고 값을 설정할 방법은 없기 때문입니다. 온도를 변경하는 유일한 방법은 메서드를 통하는 것이므로 제한 범위가 항상 유지됩니다.
파일 목록에서 thermostat.dart를 열어 수정하세요.
챌린지
중급버튼은 제한 없이 페이지에서 직접 degrees를 변경합니다. thermostat.dart에서:
- 필드 이름을
_degrees로 바꾸고, 해당 필드를 반환하는 getterdegrees를 추가합니다. - 최대 26까지 1을 더하는
warmer()와 최저 16까지 1을 빼는cooler()를 추가합니다.
그런 다음 main.dart의 버튼이 thermostat.warmer()와 thermostat.cooler()를 호출하도록 합니다.
직접 해보기
import 'package:flutter/material.dart';
import 'thermostat.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final thermostat = Thermostat();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Thermostat')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('${thermostat.degrees}°C', style: const TextStyle(fontSize: 48)),
const SizedBox(height: 16),
Row(
mainAxisSize: MainAxisSize.min,
children: [
ElevatedButton(
onPressed: () {
setState(() {
thermostat.degrees--;
});
},
child: const Text('Cooler'),
),
const SizedBox(width: 16),
ElevatedButton(
onPressed: () {
setState(() {
thermostat.degrees++;
});
},
child: const Text('Warmer'),
),
],
),
],
),
),
);
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
상태 관리의 모든 레슨
직접 연습해 보세요: 온라인 Flutter 컴파일러