Skip to content

Instantly share code, notes, and snippets.

@chooyan-eng
Created September 28, 2023 02:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chooyan-eng/51e247e1acdd51c13332bfc47c1ca8c2 to your computer and use it in GitHub Desktop.
Save chooyan-eng/51e247e1acdd51c13332bfc47c1ca8c2 to your computer and use it in GitHub Desktop.
AnimatedListView のサンプル
import 'package:flutter/material.dart';
void main() => runApp(const AnimatedListSample());
class AnimatedListSample extends StatefulWidget {
const AnimatedListSample({super.key});
@override
State<AnimatedListSample> createState() => _AnimatedListSampleState();
}
class _AnimatedListSampleState extends State<AnimatedListSample> {
// リストを操作する AnimatedListState にアクセスするための GlobalKey
final _listKey = GlobalKey<AnimatedListState>();
final _items = [0, 1, 2];
var _nextItem = 3;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('AnimatedList'),
actions: <Widget>[
IconButton(
icon: const Icon(Icons.add_circle),
onPressed: () {
final index = _items.length;
// データに追加
_items.insert(index, _nextItem);
// UI に追加
_listKey.currentState!.insertItem(index);
_nextItem++;
},
),
],
),
body: Padding(
padding: const EdgeInsets.all(16),
child: AnimatedList(
key: _listKey,
initialItemCount: _items.length,
itemBuilder: (context, index, animation) => CardItem(
animation: animation,
item: _items[index],
onDeleted: () {
// データから削除
final removedItem = _items.removeAt(index);
// UI から削除
// もしくは、AnimatedListState.of(context).removeItem でも同様
_listKey.currentState!.removeItem(
index,
(context, animation) {
// 消えるアニメーションが始まると見た目がこちらの Widget に切り替わる。
return CardItem(
animation: animation,
item: removedItem,
);
},
);
},
),
),
),
),
);
}
}
class CardItem extends StatelessWidget {
const CardItem({
super.key,
this.onDeleted,
required this.animation,
required this.item,
});
final Animation<double> animation;
final VoidCallback? onDeleted;
final int item;
@override
Widget build(BuildContext context) {
return SizeTransition(
sizeFactor: animation,
child: Card(
color: Colors.primaries[item % Colors.primaries.length],
child: Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
Expanded(
child: Text(
'Item $item',
style: Theme.of(context).textTheme.headlineMedium,
),
),
IconButton(
onPressed: onDeleted,
icon: const Icon(Icons.delete),
),
],
),
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment