Menu
CoddyTech

자식 컴포넌트에 콜백 전달하기

Coddy Flutter 여정의 상태 관리 섹션에 포함된 레슨. 27개 중 2번째.

값은 부모에서 자식으로 내려갑니다. 탭은 반대 방향으로 전달됩니다. 버튼은 자식에 있지만, 버튼이 변경하는 점수는 부모에 속합니다.

부모는 함수 하나를 자식에게 전달하고, 자식은 그 함수를 호출합니다. 매개변수가 없고 아무것도 반환하지 않는 함수의 타입은 VoidCallback입니다.

class AddButton extends StatelessWidget {
  const AddButton({super.key, required this.onAdd});

  final VoidCallback onAdd;

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(onPressed: onAdd, child: Text('Add point'));
  }
}

부모는 평소처럼 setState를 사용해 탭했을 때 할 일을 작성합니다.

AddButton(
  onAdd: () {
    setState(() {
      score++;
    });
  },
)

onAdd()가 아니라 onPressed: onAdd라고 작성하세요. 첫 번째는 나중에 사용할 수 있도록 함수를 버튼에 전달합니다. 두 번째는 위젯을 빌드하는 동안 함수를 즉시 호출하고, 함수가 반환하는 값을 전달합니다.

challenge icon

챌린지

쉬움

Add point 버튼은 AddButton 위젯에 있으며, 아직 아무 동작도 하지 않습니다.

  • AddButton에 생성자에서 설정하는 final VoidCallback onAdd 필드를 추가하세요.
  • 이 필드를 버튼의 onPressed로 사용하세요.
  • 페이지에서 setState 내부에서 score를 1 증가시키는 함수를 전달하세요.

직접 해보기

import 'package:flutter/material.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> {
  int score = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('Score: $score', style: const TextStyle(fontSize: 32)),
            const SizedBox(height: 16),
            const AddButton(),
          ],
        ),
      ),
    );
  }
}

class AddButton extends StatelessWidget {
  const AddButton({super.key});

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {},
      child: const Text('Add point'),
    );
  }
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

상태 관리의 모든 레슨

직접 연습해 보세요: 온라인 Flutter 컴파일러