[flutter] [cookbook] 위젯을 희미하게 감추기

in #kr6 years ago

출처 : https://flutter.io/docs/cookbook/animation/opacity-animation



목표

  1. fade in/out 상자 만들기
  2. StatefulWidget 정의
  3. 버튼을 통해 상자 보여주기 토글처리
  4. 상자에 fade 적용

1. fade in/out 상자 만들기

200x200 의 녹색 상자(컨테이너) 만들기

Container(
  width: 200.0,
  height: 200.0,
  color: Colors.green,
);

2. StatefulWidget 정의

StatefulWidget 은 State(상태) Object를 생성한다. 또한 이 State에는 앱에서 제공하는 데이터를 업데이트 할 수 있으며, 해당 값이 변경되면 Flutter에서는 자동으로 UI를 변경 시켜준다

// StatefulWidget 은 데이터를 가지며 State class를 생성한다 
// 이번엔, _MyHomePageState을 통해 위젯이 제목을 생성한다
class MyHomePage extends StatefulWidget {
  final String title;

  MyHomePage({Key key, this.title}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

// State class 는 2가지를 보여준다 : 데이터와 해당 데이터 변경 시 UI를 업데이트 하는 구문
class _MyHomePageState extends State<MyHomePage> {

  // 녹색 상자는 보이거나 않보임
  bool _visible = true;

  @override
  Widget build(BuildContext context) {
    // 녹색상자 관련 코딩은 이곳에 위치한다
  }
}

3. 버튼을 통해 상자 보여주기 토글처리

데이터 값의 변화를 통해 상자를 보여주거나 않보여 주도록 처리하며, 이를 위해 버튼을 추가 하여 상태값을 토글(활성화<->비활성화) 처리하여 상태값을 설정하며, flutter는 이를 감지해 Widget을 재 생성한다

FloatingActionButton(
  onPressed: () {
    // setState() 호출을 통해 값을 설정하며
    // 이를 값의 변경 감지를 통해 flutter는 UI를 재빌드 한다.
    setState(() {
      _visible = !_visible;
    });
  },
  tooltip: 'Toggle Opacity',
  child: Icon(Icons.flip),
);

4. 상자에 fade 적용

_visible 값의 변화에 따라 불투병도를 변화 시킨다

AnimatedOpacity(
  // 위젯이 보이면(visible) 0 => 1.0 불투명도 에니메이션 처리
  // 위젯이 감춰지면(hidden) 1.0 => 0 불투명도 에니메이션 처리
  opacity: _visible ? 1.0 : 0.0,
  duration: Duration(milliseconds: 500),  
  // 녹색상자는 AnimatedOpacity의 자식(child)으로 지정
  child: Container(
    width: 200.0,
    height: 200.0,
    color: Colors.green,
  ),
);

5. 완성된 예제

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appTitle = 'Opacity Demo';
    return MaterialApp(
      title: appTitle,
      home: MyHomePage(title: appTitle),
    );
  }
}

// The StatefulWidget's job is to take in some data and create a State class.
// In this case, our Widget takes in a title, and creates a _MyHomePageState.
class MyHomePage extends StatefulWidget {
  final String title;

  MyHomePage({Key key, this.title}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

// The State class is responsible for two things: holding some data we can
// update and building the UI using that data.
class _MyHomePageState extends State<MyHomePage> {
  // Whether the green box should be visible or invisible
  bool _visible = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: AnimatedOpacity(
          // If the Widget should be visible, animate to 1.0 (fully visible). If
          // the Widget should be hidden, animate to 0.0 (invisible).
          opacity: _visible ? 1.0 : 0.0,
          duration: Duration(milliseconds: 500),
          // The green box needs to be the child of the AnimatedOpacity
          child: Container(
            width: 200.0,
            height: 200.0,
            color: Colors.green,
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // Make sure we call setState! This will tell Flutter to rebuild the
          // UI with our changes!
          setState(() {
            _visible = !_visible;
          });
        },
        tooltip: 'Toggle Opacity',
        child: Icon(Icons.flip),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

맺음말

  • 일단 스터디 가즈앙~

관련글


Sponsored ( Powered by dclick )

dclick-imagead

Sort:  

이게 뭐하는 건가요?
일단 스터디 가즈앙~ ? 전 싫은데요!! ㅋㅋ

쉽지않은 스터디 ㅋㅋ

flutter를 해보려고 관련 프로그램들 설치하는데 맥북용량이 꽉 찼다네요. ㅋㅋㅋㅋ
핑계거리가 생겨서 못하고 있습니다.ㅋㅋㅋㅋㅋ

이런... 굳 라이벌 한명 줄었음 ㅎㅎ

저도 맥북용량 꽉차서 못하고 있네요.ㅋㅋ

이건 안드로이드? 에서 사용 하는건가용?
간단해 보이네요 ㅋㅋ 제손으로 안해서 그런지

둘 다 가능요

하이브리드 네이티브 앱 개발요 ㅋ

Hi @wonsama!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your UA account score is currently 3.685 which ranks you at #5201 across all Steem accounts.
Your rank has dropped 41 places in the last three days (old rank 5160).

In our last Algorithmic Curation Round, consisting of 217 contributions, your post is ranked at #46.

Evaluation of your UA score:
  • You're on the right track, try to gather more followers.
  • The readers like your work!
  • Good user engagement!

Feel free to join our @steem-ua Discord server

일단 스터디 가즈앙~~~!!
도전해보겠습니다 ㅎㅎ

도전은 늘 아름답습니다 :)

애니매이션이 간단한 코드로 되네요. 플러터 스터디 가즈아~! ㅋ

간단하게 가즈앙 ~

빨리 빨리 다음 강좌 가즈아~

다음 강좌도 후다닥 해봐야죠 ㅋ

Coin Marketplace

STEEM 0.28
TRX 0.12
JST 0.033
BTC 70013.82
ETH 3766.83
USDT 1.00
SBD 3.80