Skip to content

Instantly share code, notes, and snippets.

@RyouMon
Created December 25, 2022 14:23
Show Gist options
  • Save RyouMon/ae56e3f902b0798a50e1820cf94e5a0c to your computer and use it in GitHub Desktop.
Save RyouMon/ae56e3f902b0798a50e1820cf94e5a0c to your computer and use it in GitHub Desktop.
Flutter Demo: AnimatedList Example
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class AnimatedListRoute extends StatefulWidget {
const AnimatedListRoute({super.key});
@override
State<AnimatedListRoute> createState() => _AnimatedListRouteState();
}
class _AnimatedListRouteState extends State<AnimatedListRoute> {
var data = <String>[];
int counter = 5;
final globalkey = GlobalKey<AnimatedListState>();
@override
void initState() {
for (var i = 0; i < counter; i++) {
data.add('${i + 1}');
}
super.initState();
}
@override
Widget build(BuildContext context) {
return Stack(
children: [
AnimatedList(
key: globalkey,
initialItemCount: data.length,
itemBuilder: (context, index, animation) => FadeTransition(
opacity: animation,
child: buildItem(context, index),
),
),
Positioned(
bottom: 30,
left: 0,
right: 0,
child: FloatingActionButton(
onPressed: (() {
data.add('${++counter}');
globalkey.currentState!.insertItem(data.length - 1);
}),
child: const Icon(Icons.add),
))
],
);
}
Widget buildItem(context, index) {
String char = data[index];
return ListTile(
key: ValueKey(char),
title: Text(char),
trailing: IconButton(
icon: const Icon(Icons.delete),
onPressed: () => onDelete(context, index),
),
);
}
void onDelete(context, index) {
setState(() {
globalkey.currentState!.removeItem(index, (context, animation) {
var item = buildItem(context, index);
data.removeAt(index);
return FadeTransition(
opacity: CurvedAnimation(
curve: const Interval(0.5, 1.0), parent: animation),
child: SizeTransition(
sizeFactor: animation,
axisAlignment: 0.0,
child: item,
),
);
}, duration: const Duration(microseconds: 500));
});
}
}
class HomePage extends StatelessWidget {
const HomePage({super.key, required this.title});
final String title;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(title)),
body: const AnimatedListRoute(),
);
}
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const HomePage(title: 'AnimatedList Example'),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment