どうも、ちょげ(@chogetarou)です。
テキストスタイルを切り替えるアニメーションをする方法を紹介します。
方法
AnimatedDefaultTextStyle(
child: Text('Flutter'),
style: animated
? TextStyle(
color: Colors.blue,
fontSize: 36,
)
: TextStyle(
color: Colors.grey,
fontSize: 14,
),
duration: Duration(seconds: 1),
),
まず、TextStyleを切り替えるための変数を用意します。
bool animated = false;
そして、テキストスタイルの切り替えをするためにはm「AnimatedDefaultTextStyle」を使います。
AnimatedDefaultTextStyle(
child: Text('Flutter'), //テキスト
style: animated
? TextStyle(
color: Colors.blue,
fontSize: 36,
)
: TextStyle(
color: Colors.grey,
fontSize: 14,
),
duration: Duration(seconds: 1), //アニメーションの時間
),
ポイントは、引数「style」を条件分岐で切り替える点です。
三項演算(?:)と先ほど用意した変数を使い、テキストスタイルが切り替わるようにしています。
あとは、変数の値を変更する処理を追加すれば完了です。
ElevatedButton(
onPressed: () {
setState(() {
animated = !animated;//変数の切り替え
});
},
child: Text('Switch'),
)
全体のコード
bool animated = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Sample'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
AnimatedDefaultTextStyle(
child: Text('Flutter'),
style: animated
? TextStyle(
color: Colors.blue,
fontSize: 36,
)
: TextStyle(
color: Colors.grey,
fontSize: 14,
),
duration: Duration(seconds: 1),
),
ElevatedButton(
onPressed: () {
setState(() {
animated = !animated;
});
},
child: Text('Switch'),
)
],
),
));
}
コメント