默认情况下,当 a 发生状态更改时StatefulWidget,状态转换没有动画。有什么办法可以吃一些吗?例如,在转换时,我想淡出旧状态并淡入新状态。
我知道如何在路线之间添加过渡动画,但找不到在状态转换之间执行此操作的方法。
有一个例子,让我们使用 Flutter 默认应用程序:
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: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
Run Code Online (Sandbox Code Playgroud)
因此,每次我单击按钮时,数字都会立即更改。我希望看到的是旧号码淡出,新号码淡入。
这个答案,使用AnimatedOpacity效果很好。但我发现使用起来AnimatedSwitcher更加简单和干净。
(...)
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
AnimatedSwitcher(
duration: const Duration(milliseconds: 500),
transitionBuilder: (Widget child, Animation<double> animation) {
return FadeTransition(child: child, opacity: animation);
},
child: Text(
'$_counter',
key: ValueKey<int>(_counter),
style: Theme.of(context).textTheme.display1,
),
),
],
),
),
(...)
Run Code Online (Sandbox Code Playgroud)
有关 的更多信息,请参阅此处AnimatedSwitcher。
| 归档时间: |
|
| 查看次数: |
9659 次 |
| 最近记录: |