问题描述
这里是my code as a gist(an interactive version of my code in dartpad.dev)
关于我正在尝试使用此应用做什么的简短摘要:
我有两个页面
的/
,我想在TextField中键入一个字符串,该字符串将同时开始出现在appBar
中,还有另一个按钮,当您按下时,它将带您进入到另一个页面(Home
小部件),但带有您在text
页面中编写的/
。我希望这种过渡像英雄动画一样,其中文本从appBar
页面/
的{{1}}到flies
body
我以前正在使用
Info
要转到新页面并传递要显示的文本。我能够做到这一点,但是即使在“个人档案”模式下,动画也太快了
但是我从this Question得到的答案是使用
Navigator.pushNamed(context,"Info",arguments: {"text": myController.text});
但是问题是,Navigator.push(
context,PageRouteBuilder(
transitionDuration: Duration(seconds: 2),pageBuilder: (_,__,___) => Page2())
),
不允许您传递参数,我当然希望能够这样做。
解决方法
如果您可以使用PageRouteBuilder class控制过渡动画,那么您唯一关心的就是传递数据。现在,我敢肯定,您已经错过了,这是:
将数据作为Flutter中类的参数传递。您实际上不必总是
arguments: {}
这样的东西。
现在,我的意思是,Flutter中的每个类都可以接受数据作为参数,你怎么做。
- 创建一个接受参数的内容[您已经完成了此操作]
- 在使用时,在我们的案例
Info(pass_it_here)
中,在类中传递数据[必须立即完成]
我们如何用代码实现?
因此,您只需在过渡时像下面提到的那样传递数据即可。您的Info类可以接受数据。因此,您要做的就是实现您想要的目标,
Navigator.push(
context,PageRouteBuilder(
transitionDuration: Duration(seconds: 2),pageBuilder: (_,__,___) => Info(text: myController.text) // <-- here is the magic
)
)
建议:
如果要为类定义参数,让我们仅以Info
为例,请将其声明为final。我知道您将更改数据,但是您可以将内容复制到本地变量,然后执行所需的任何操作。
示例
class Info extends StatefulWidget {
final String text; // <-- Declare this as final
Info({this.text});
@override
_InfoState createState() => _InfoState();
}
在主类中使用@immutable数据:
class _InfoState extends State<Info> {
// here how you are just copying the data to the local variable
// var _myText = widget.text;
String _myText = "";
// or you can do this via @initState
@override
void initState(){
super.initState();
_myText = widget.text;
}
// Now use your variable _myText however you want
}