启动画面颤动,防止返回按钮

Posted

技术标签:

【中文标题】启动画面颤动,防止返回按钮【英文标题】:Splashscreen flutter, prevent back button 【发布时间】:2022-01-01 05:25:17 【问题描述】:

我已经制作了一个自定义 Splashscreen,但是当我从 statless 小部件按下返回按钮时,它会返回 Splashcreen“有状态小部件”。我已经尝试过 WillPopBack 但它不起作用,或者至少我无法使用它。如何防止无状态小部件返回有状态小部件? 这是我的代码:

void main() 
  runApp(const MyApp());


class MyApp extends StatelessWidget 
  const MyApp(Key? key) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) 
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(primarySwatch: Colors.blue, fontFamily: 'Monserrat'),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  


class MyHomePage extends StatefulWidget 
  const MyHomePage(Key? key, required this.title) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();


class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin 
  @override
  void initState() 
    super.initState();
    Future.delayed(Duration(seconds: 4), () 
      Navigator.of(context).push(
        PageRouteBuilder(
          transitionDuration: Duration(milliseconds: 1000),
          pageBuilder: (BuildContext context, Animation<double> animation,
              Animation<double> secondaryAnimation) 
            return MainScreen();
          ,
          transitionsBuilder: (BuildContext context,
              Animation<double> animation,
              Animation<double> secondaryAnimation,
              Widget child) 
            return Align(
              child: FadeTransition(
                opacity: animation,
                child: child,
              ),
            );
          ,
        ),
      );
    );
  

  @override
  Widget build(BuildContext context) 
    return [...]
  


class MainScreen extends StatelessWidget 

  @override
  Widget build(BuildContext context) 
    return [...]
  


提前致谢

【问题讨论】:

【参考方案1】:

使用pushReplacement 代替push 喜欢

  super.initState();
    Future.delayed(Duration(seconds: 4), () 
      Navigator.of(context).pushReplacement( //< this
        PageRouteBuilder(
          transitionDuration: Duration(milliseconds: 1000),
          pageBuilder: (BuildContext context, Animation<double> animation,
              Animation<double> secondaryAnimation) 
            return MainScreen();
          ,

更多关于push和pushReplacement

【讨论】:

以上是关于启动画面颤动,防止返回按钮的主要内容,如果未能解决你的问题,请参考以下文章

在颤动中打开对话框时检测返回按钮按下

如何在颤动中拦截AppBar中的后退按钮

如何制作一个包含在整个屏幕上拉伸的背景图像的颤动应用程序,带有返回句子的图像的圆形按钮?

程序启动画面

如何在flutter中停用或覆盖appBar中的箭头后退按钮?

在颤动中隐藏后退按钮