弹出式作用域小部件仅适用于我项目的最后一个屏幕,我想在每个页面或特定页面上使用它

时间:2019-09-04 16:52:10

标签: flutter dart flutter-layout

我已经为启动屏幕和主屏幕编写了代码,我的自定义启动屏幕在3秒钟后都在两个屏幕上都应用了WillPopScope,但导航到了主屏幕,但它仅在启动屏幕上有效。当我禁用启动并仅运行主屏幕时,WillPopScope效果很好,但是当我应用启动屏幕时,它在主屏幕上不起作用。我想在主屏幕和一个Webview屏幕上拥有此类功能,该如何使用?

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:splashscreen/splashscreen.dart';
import 'dart:async';
import 'main.dart';

void main() {
  runApp(
      MaterialApp(
    home: splash(),
  ));
}

class splash extends StatefulWidget {
  @override
  _splashState createState() => new _splashState();
}

class _splashState extends State<splash> {

  void initState() {
    super.initState();
    Timer(
        Duration(seconds: 3),
        () => Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => MyApp()),
            ));
  }

  @override
  Widget build(BuildContext context) {
    Future<bool> _onBackPressed() {
      return showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: Text("Do you want to exit?"),
            actions: <Widget>[
              FlatButton(
                  onPressed: () {
                    Navigator.pop(context, false);
                  },
                  child: Text("No")),
              FlatButton(
                  onPressed: () {
                    Navigator.pop(context, true);
                  },
                  child: Text("yes"))
            ],
          ));
    }
    Orientatoin();
    return WillPopScope(
      child: Scaffold(
      body: Stack(
        fit: StackFit.expand,
        children: <Widget>[
          Container(
            decoration: BoxDecoration(
              color: Colors.transparent,
            ),
            child: Image.asset('imges/splash.png'),
          ),
        ],
      ),
    ),
      onWillPop: _onBackPressed,

      );
  }
}

void Orientatoin() {
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
}

1 个答案:

答案 0 :(得分:0)

在您的代码中,编辑Navigator代码以将{初始页面}替换为MyApp()

Timer(
        Duration(seconds: 3),
            () => Navigator.pushReplacement(
          context,
          MaterialPageRoute(builder: (context) => MyApp()),
        ));

在您的WillPopScope中添加MyApp()