기본 Layout 예제 만들기 (5)
2022. 6. 10. 00:00ㆍFlutter
반응형
사용자 입력에 반응 하도록 앱 수정하기
우선 위와 같이 빨간색으로 칠해진 별을 클릭하면 count 가 41 에서 40 으로 바뀌고
별모양도 태두리만 있고 안쪽은 비어 있는 상태가 되도록 만들어 보자
상태를 관리 하기 위해 stateful widget 을 생성하자
(상태를 관리하는 다른 방법들도 있다. bloc , provider, riverpod 등등
하지만 여기서는 가장 기본적인 상태관리 방법인 stateful widget 을 사용해보자)
lib/main.dart (FavoriteWidget)
class FavoriteWidget extends StatefulWidget {
const FavoriteWidget({super.key});
@override
_FavoriteWidgetState createState() => _FavoriteWidgetState();
}
lib/main.dart(_FavoriteWidgetState)
class _FavoriteWidgetState extends State<FavoriteWidget> {
bool _isFavorited = true;
int _favoriteCount = 41;
void _toggleFavorite() {
setState(() {
if (_isFavorited) {
_favoriteCount -= 1;
_isFavorited = false;
} else {
_favoriteCount += 1;
_isFavorited = true;
}
});
}
@override
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
padding: const EdgeInsets.all(0),
child: IconButton(
padding: const EdgeInsets.all(0),
alignment: Alignment.centerRight,
icon: (_isFavorited
? const Icon(Icons.star)
: const Icon(Icons.star_border)),
color: Colors.red[500],
onPressed: _toggleFavorite,
),
),
SizedBox(
width: 18,
child: SizedBox(
child: Text('$_favoriteCount'),
),
),
],
);
}
}
titleSection 을 다음과 같이 수정한다.
...
final Widget titleSection = Container(
padding: const EdgeInsets.all(32),
child: Row(
children: [
...
/*3*/
// Icon(
// Icons.star,
// color: Colors.red[500],
// ),
// const Text('41'),
const FavoriteWidget(), // add
],
),
);
...
초기 실행
별 클릭시 상호작용
관련영상
반응형
'Flutter' 카테고리의 다른 글
명명된 경로(named routes) 를 이용한 페이지이동 (0) | 2022.06.14 |
---|---|
페이지 이동 (0) | 2022.06.13 |
기본 Layout 예제 만들기 (4) (0) | 2022.06.09 |
기본 Layout 예제 만들기 (3) (0) | 2022.06.08 |
기본 Layout 예제 만들기 (2) (0) | 2022.06.07 |