Created
April 28, 2019 08:46
-
-
Save CaiJingLong/20d9a726d2b753af6fd431285f486eef to your computer and use it in GitHub Desktop.
flutter_AnimatedList_example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
// This widget is the root of your application. | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: AnimPage(), | |
); | |
} | |
} | |
class AnimPage extends StatefulWidget { | |
@override | |
_AnimPageState createState() => _AnimPageState(); | |
} | |
class _AnimPageState extends State<AnimPage> { | |
GlobalKey<AnimatedListState> key = GlobalKey(); | |
var items = List<int>.generate(100, (i) => i); | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
actions: <Widget>[ | |
IconButton( | |
icon: Icon(Icons.add), | |
onPressed: _add, | |
), | |
IconButton( | |
icon: Icon(Icons.remove), | |
onPressed: _remove, | |
), | |
], | |
), | |
body: AnimatedList( | |
key: key, | |
itemBuilder: _buildItem, | |
initialItemCount: items.length, | |
), | |
); | |
} | |
void _remove() { | |
items.removeAt(3); | |
key.currentState.removeItem( | |
3, | |
(ctx, anim) => _buildRemoveAnim(ctx, anim, 3), | |
); | |
} | |
void _add() { | |
items.insert(1, 3939); | |
key.currentState.insertItem(1, duration: Duration(seconds: 1)); | |
} | |
Widget _buildItem( | |
BuildContext context, | |
int index, | |
Animation<double> animation, | |
) { | |
var item = items[index]; | |
return ScaleTransition( | |
child: Container( | |
child: Text( | |
item.toString(), | |
style: const TextStyle(fontSize: 30), | |
), | |
height: 60, | |
alignment: Alignment.center, | |
), | |
scale: animation, | |
); | |
} | |
Widget _buildRemoveAnim( | |
BuildContext context, Animation<double> animation, int index) { | |
var item = items[index]; | |
return SlideTransition( | |
child: Container( | |
child: Text( | |
item.toString(), | |
style: const TextStyle(fontSize: 30), | |
), | |
height: 60, | |
alignment: Alignment.center, | |
), | |
position: convert(animation), | |
); | |
} | |
Animation<Offset> convert(Animation<double> animation) { | |
return Tween<Offset>( | |
begin: Offset(1, 0), | |
end: Offset(0, 0), | |
).animate(animation); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment