본문 바로가기
카테고리 없음

플러터 기본 위젯 예제(MaterialWidget) - StatefulWidget

by prlkt5200 2024. 8. 1.
반응형

 

많은 분들에게 기본적인 도움이라도 되길 바라며, 학습 목적 외에 상업적 이용은 금합니다. 

 

출처: 패스트캠퍼스 15개 프로젝트로 실무까지 끝내는 Dart & Fultter 앱 개발, 챗 gpt

출처: https://forfire700.tistory.com/152 [IT STUDY CAFE:티스토리]


코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
 
const assetImagePath = 'assets/images';
const bannerImage = '$assetImagePath/banner.png';
 
void main() {
  runApp(
    MaterialApp(
      home: Body(),
    ),
  );
}
 
class Body extends StatelessWidget {
  const Body({super.key});
 
  @override
  Widget build(BuildContext context) {
    return const Column(children: [
      ExampleStateless(),
      ExampleStateful(index: 3),
    ]);
  }
}
 
class ExampleStateless extends StatelessWidget {
  const ExampleStateless({super.key});
 
  @override
  Widget build(BuildContext context) {
    return Expanded(
        child: Container(
      color: Colors.red,
    ));
  }
}
 
class ExampleStateful extends StatefulWidget {
  final int index;
 
  const ExampleStateful({required this.index, super.key});
 
  @override
  State<ExampleStateful> createState() => _ExampleStatefulState();
}
 
class _ExampleStatefulState extends State<ExampleStateful> {
  late int _index;
  late TextEditingController textController;
  @override
  void initState() {
    super.initState();
    _index = widget.index;
    textController = TextEditingController();
  }
 
  @override
  void dispose() {
    textController.dispose();
    super.dispose();
  }
 
  @override
  Widget build(BuildContext context) {
    return Expanded(
      flex: 1,
      child: GestureDetector(
        onTap: () {
          setState(() {
            if (_index == 5) {
              _index = 0;
              return;
            }
            _index++;
          });
        },
        child: Container(
            color: Colors.blue.withOpacity(_index / 5),
            child: Center(child: Text('$_index'))),
      ),
    );
  }
}
 
cs

 

반응형