플러터 공식 유튜브엔, 플러터에 관한 여러가지 정보들이 있다.
< 플러터 공식 유튜브 - 이주의 위젯 카테고리 >
Flutter Widget of the Week
Fighting the good fight for Widget Awareness! Widget of the Week is a series of quick, animated videos, each of which covers a particular widget from the Flu...
www.youtube.com
이중, 이주의 위젯 카테고리에는 여러 새로운 위젯들이 있는데, 이들을 탐방해 보고자 한다!
** 정리 순서 - 간단한 설명, 사용법, 관련공식문서링크
** 볼때마다 추가 예정 (옛날것부터 정리할 예정)
- Opacity
자식 위젯을 투명하게 만드는 위젯
이 위젯은 자식 위젯을 중간 버퍼에 그린다음, 해당 자식을 화면에 일부 투명하게 혼합하여 다시 렌더링 하는 형태로 구현한다.
즉, Opacity 위젯은 어떤 위젯이든 투명도를 넣을 수 있는 장점이 있는 반면, 자식 위젯에다가 직접적으로 투명도를 설정하는 방법보다 성능적인 면에서는 좋지 않다!
// 정의
const Opacity({
super.key,
required this.opacity,
this.alwaysIncludeSemantics = false,
super.child,
}) : assert(opacity >= 0.0 && opacity <= 1.0);
// 사용법
Opacity(
opacity: 0.8,
child: const Text("투명도 0.8!!"),
)
Opacity class - widgets library - Dart API
A widget that makes its child partially transparent. This class paints its child into an intermediate buffer and then blends the child back into the scene partially transparent. For values of opacity other than 0.0 and 1.0, this class is relatively expensi
api.flutter.dev
- FutureBuilder
## FutureBuilder는 Take2 버전(업데이트버전)이 있으므로, 해당 버전을 기준으로 설명함 (32번 영상)
Future와의 상호작용을 통해서 얻은 최신 스냅샷을 기반으로 자체적으로 빌드되는 위젯.
즉, 설정한 Future의 상태를 감시하고, 상태 변화에 따라 위젯을 업데이트 및 빌드할 수 있도록 하는 위젯이라고 할 수 있다.
여기서 스냅샷은 객체의 상태를 확인하는데 사용되는 클래스이다.
// 정의
const FutureBuilder({
super.key,
required this.future,
this.initialData,
required this.builder,
});
// 사용법 1
// snapshot을 이용해 데이터가 전달된 타이밍에 UI를 업데이트 하고자 할 경우
// 설정할 Future(비동기 작업)
Future<String> fetchData() async {
await Future.delayed(Duration(seconds: 2));
return 'Hello, FutureBuilder!';
}
@override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: fetchData(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator(); // 로딩상태
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}'); // 에러상태
} else if (snapshot.hasData) {
return Text(snapshot.data!); // 성공상태
} else {
return Text('No data'); // 기본상태
}
},
);
}
// 사용법 2
// snapshot.connectionState 를 통해 실시간 future의 상태를 확인하여 UI를 업데이트 할 경우
// 설정할 Future(비동기 작업)
Future<String> fetchData() async {
await Future.delayed(Duration(seconds: 2));
return 'Hello, FutureBuilder!';
}
FutureBuilder<String>(
future: fetchData(),
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('No Future set.');
case ConnectionState.waiting:
return CircularProgressIndicator(); // 로딩 상태
case ConnectionState.active:
return Text('Still active...'); // Future가 진행 중일 때 (드물게 사용됨)
case ConnectionState.done:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}'); // 에러 처리
} else {
return Text('Result: ${snapshot.data}'); // 성공 결과 표시
}
}
},
)
FutureBuilder class - widgets library - Dart API
A widget that builds itself based on the latest snapshot of interaction with a Future. Managing the future The future must have been obtained earlier, e.g. during State.initState, State.didUpdateWidget, or State.didChangeDependencies. It must not be create
api.flutter.dev
- FadeTransition
위젯의 Opacity 값을 애니메이션으로 조정하는 위젯
자매품으로 ScaleTransition, SlideTransition 등이 있으며, 동작방식은 동일하다.
## 추가 AnimatedWidget과 Transition의 차이점
AnimatedWidget은 Animation 상태를 직접 위젯에 결합하여 사용하는 클래스로써, AnimationController를 통해 보다 복잡한 Animation을 사용하고자 할때 주로 사용되는 범용적인 위젯이라고 할 수 있다.
반면, Transition은 각각 Fade, Scale 등등처럼 해당 기능만 한정된 애니메이션 기능을 사용하고자 할때 사용되며, 플러터에서 보다 간편하게 사용하라고 제공한 위젯인 만큼, 같은 기능 구현에 있어 보다 간단하게 코드작성이 가능하다.
// 정의
const FadeTransition({
super.key,
required this.opacity,
this.alwaysIncludeSemantics = false,
super.child,
});
// 사용법
// StatefulWidget
class _FadeTransitionExampleState extends State<FadeTransitionExample> with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _animation;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: Duration(seconds: 2),
vsync: this,
)..repeat(reverse: true);
_animation = CurvedAnimation(
parent: _controller,
curve: Curves.easeInOut,
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: FadeTransition(
opacity: _animation, // 투명도 애니메이션
child: Text(
"Fading!",
style: TextStyle(fontSize: 32, fontWeight: FontWeight.bold),
),
),
),
);
}
FadeTransition class - widgets library - Dart API
Animates the opacity of a widget. For a widget that automatically animates between the sizes of two children, fading between them, see AnimatedCrossFade. Here's an illustration of the FadeTransition widget, with it's opacity animated by a CurvedAnimation s
api.flutter.dev
'Flutter' 카테고리의 다른 글
Flutter 이주의 위젯 탐방 (4) - SliverAppBar, SliverList, SliverGrid (0) | 2024.11.21 |
---|---|
Flutter 이주의 위젯 탐방 (3) - FloatingActionButton, PageView, Table (0) | 2024.11.20 |
Flutter 이주의 위젯 탐방 (1) - SafeArea, Expanded, Wrap, AnimatedContainer (0) | 2024.11.18 |
실전예제4 - BMI 앱 만들기 (0) | 2024.11.12 |
실전예제3 - 좌석앱 만들기 (0) | 2024.11.12 |