从外部将初始参数赋予Statefulwidget

时间:2020-09-05 01:54:09

标签: flutter

我想用字符串“ mytitle”,“ Anime”制作Page Widget

这个问题可能太简单了,但对我来说,StatefulWidgetState的关系非常混乱

return Navigator.pushReplacement(context,
     NoAnimationMaterialPageRoute(
      builder: (context,"mytitle","Anime") => AnimePage()));

class AnimePage extends StatefulWidget {
  AnimePage({Key key, this.title, this.video}) : super(key: key);
  final String title;
  final String video;

  @override
  _AnimePageState createState() => _AnimePageState();
}

class _AnimePageState extends State<AnimePage> {
  @override
  void initState() {
    super.initState();
    print(widget.video) //want to show `Anime` here
    };

2 个答案:

答案 0 :(得分:1)

这有效:

   return Navigator.pushReplacement(
      context,
      NoAnimationMaterialPageRoute(
        builder: (context) => AnimePage(
          // pass your parameter values
          title: 'My Anime',
          video: YOUR_VIDEO_PARAM,
        ),
      ),
    );

答案 1 :(得分:0)

您还必须在State上添加构造函数,像这样...

class AnimePage extends StatefulWidget {
  AnimePage({Key key, this.title, this.video}) : super(key: key);
  final String title;
  final String video;

  @override
  _AnimePageState createState() => _AnimePageState(title,video);
}

class _AnimePageState extends State<AnimePage> {
  final String title;
  final String video;

  _AnimePageState(this.title,this.video);

  @override
  void initState() {
    super.initState();
    print(widget.video) //want to show `Anime` here
    };

我希望这就是您要寻找的