Flutterのウィジェット「AnimatedAlign」の使い方を紹介します。
「AnimatedAlign」を使えば指定したウィジェットの位置をアニメーションを使用して再配置できます。
目次
AnimatedAlignの使い方
アニメーションを使用して再配置したいウィジェットを「AnimatedAlign」でラップし「duration」でアニメーションの時間、「alignment」で子要素の位置を指定します。
下記コードでは「alignment」に三項演算子を使用し、「GestureDetector」で「Container」がタップされる度に「alignment」の値が変化するようにしています。
class _MyAppState extends State<MyApp> {
bool _flag = true;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Flutter')),
body: GestureDetector(
onTap: () {
setState(() {
_flag = !_flag;
});
},
child: Center(
child: Container(
width: 250.0,
height: 250.0,
color: Colors.red,
child: AnimatedAlign(
alignment: _flag ? Alignment.topRight : Alignment.bottomLeft,
duration: Duration(seconds: 1),
curve: Curves.fastOutSlowIn,
child: FlutterLogo(size: 50.0),
),
),
),
),
),
);
}
}
サンプルコード
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool _flag = true;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Flutter')),
body: GestureDetector(
onTap: () {
setState(() {
_flag = !_flag;
});
},
child: Center(
child: Container(
width: 250.0,
height: 250.0,
color: Colors.red,
child: AnimatedAlign(
alignment: _flag ? Alignment.topRight : Alignment.bottomLeft,
duration: Duration(seconds: 1),
curve: Curves.fastOutSlowIn,
child: FlutterLogo(size: 50.0),
),
),
),
),
),
);
}
}
以上です。
合わせて読みたい
あわせて読みたい


【Flutter】AnimatedSwitcherの使い方|アニメーションで表示切り替え
Flutterのウィジェット「AnimatedSwitcher」の使い方を紹介します。 「AnimatedSwitcher」を使えばアニメーションで表示されているウィジェットを切り替えできます。 An…
あわせて読みたい


【Flutter】Durationの使い方|時間・期間の指定
こんにちは、フラメルです。 今回はアニメーション時間や期間を指定する際に使用されるDurationの使い方を紹介します。 Durationの基本的な使い方 Durationでは下記コー…
あわせて読みたい


【Flutter】AnimatedOpacityの使い方|透明度をアニメーションで変更
こんにちは、フラメルです。 今回は任意のウィジェットの透明度をアニメーションで徐々に変更できるAnimatedOpacityの使い方を紹介します。 アニメーションで透明度を徐…