const 위젯
Coddy Flutter 여정의 앱에 상호작용 추가하기 섹션에 포함된 레슨. 34개 중 15번째.
값 앞에 있는 const는 코드를 작성할 때 값이 고정되며 절대 바뀌지 않는다는 뜻입니다. 앱이 실행되는 동안 const Text('Score')는 Score를 표시합니다.
Dart에 왜 이런 사실을 알려 줄까요? setState가 화면을 다시 빌드할 때 Flutter는 그 안의 어떤 것도 바뀌지 않았다는 것을 알기 때문에 모든 const 위젯을 건너뛸 수 있습니다. 그래서 VS Code와 Android Studio 같은 Flutter 코드 편집기는 const로 만들 수 있는 위젯에 밑줄을 긋고 추가하라고 제안합니다. 이제부터 이 과정의 앱에서는 적절한 곳에 const를 사용합니다.
const는 안쪽에도 적용됩니다. 위젯에 붙이면 괄호 안의 모든 요소도 const가 됩니다. 따라서 바뀌지 않는 가장 바깥쪽 위젯에 한 번만 쓰면 됩니다.
const Column(
children: [
Text('Score'),
Icon(Icons.star),
],
)변수는 바뀔 수 있으므로 const 안에 절대 넣을 수 없습니다. 해당 열에 Text('$_score')를 넣으면 Dart는 "Not a constant expression" 오류와 함께 컴파일을 거부합니다. 해결 방법은 열에서 const를 떼고 바뀌지 않는 각 자식 요소에 붙이는 것입니다.
Column(
children: [
const Text('Score'),
Text('$_score'),
],
)챌린지
중급플러스 버튼을 누르면 점수가 올라가지만 화면에는 표시되지 않습니다. Score 아래에 크기 48인 Text('$_score')를 추가하세요. 변경되지 않는 위젯들에 Column의 const를 옮겨야 합니다.
직접 해보기
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: const HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int _score = 0;
void _goal() {
setState(() {
_score++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Game')),
body: Center(
child: const Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.sports_soccer, size: 64),
Text('Score', style: TextStyle(fontSize: 24)),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _goal,
child: const Icon(Icons.add),
),
);
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
앱에 상호작용 추가하기의 모든 레슨
직접 연습해 보세요: 온라인 Flutter 컴파일러