首页 > 解决方案 > Flutter App 在我使用设备后退按钮关闭后启动时崩溃

问题描述

对不起!!这个问题可能是重复的,但我无法找到解决方案。这是我的问题,我完成了我的颤振应用程序,几乎一切工作正常,但有一个问题。我使用设备后退按钮关闭应用程序,当我再次打开它时,第一次打开白屏,然后打开第二个黑屏并停留在那个黑屏(卡在黑屏上)应用程序崩溃

这里有你需要的一切。

我的文件夹结构是,用户 SIGNUP() 或 login(),我有一个登录和注册页面(),当用户按下登录或注册按钮时,他从登录或注册页面转到 HomeControllerpage() 页面 HomeControllerPage() 是如果用户通过身份验证,则对用户进行身份验证并重定向到 homePage() 的页面。否则,如果用户未通过身份验证,用户将再次重定向到登录/注册页面

Here is my Main.dart

void main()async{
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp().catchError((e) {
    print(e);

  });
  runApp(
      Myapp());
  
}
class Myapp extends StatefulWidget {
  @override
  State<Myapp> createState() => _MyappState();
}

class _MyappState extends State<Myapp> {

  @override
  Widget build(BuildContext context) {
        return Provider(
          auth: Authservice(),
        child: MaterialApp(
       title: 'signup',
        theme: ThemeData(
          primarySwatch: Colors.green,
        ),
          initialRoute:  '/home',
          debugShowCheckedModeBanner: false,
        //flutter  home:email==null? homecontroller(controllUserType: 'hfdd',):null,
          routes: <String,WidgetBuilder>{
          '/home':(BuildContext context)=>homecontroller(),
         '/Signup':(BuildContext context)=>signup_view(authFormType: AuthFormType.Signup,),
          '/SignIn':(BuildContext context)=>signup_view(authFormType: AuthFormType.SignIn,),
         '/dropDown':(BuildContext context)=>dropDown()//delet this
        },
      ),
    );
  }

}

 Here is how the user Signup, Signup() page

     Future<String> CreateUserUisngEmailAndPassword(
          BuildContext context,
        String _firstname,
        String _userID,
        String _dropDownValue,
      ) async {
        try {
          final UserCredential Newuser = await _firebaseAuth
              .createUserWithEmailAndPassword(email: email, password: _password);
          User curentRegistereduser = Newuser.user;
          await AddToDataBase(uid: curentRegistereduser.uid).firebaseuserdata(
              _firstname,
              _userID=curentRegistereduser.uid,
          );
    
          Navigator.of(context).pushReplacement(
              MaterialPageRoute(builder: (context)=>homecontroller(
                controllUserType:_dropDownValue,
                userid:_userID,
              )));
        }on FirebaseAuthException catch (e) {
          if (e.code == 'weak-password') {
            print('The password provided is too weak.');
          } else if (e.code == 'email-already-in-use') {
            print('The account already exists for that email.');
          }
        } catch (e) {
          print(e);
        }
        //Update User
      }

Here is How user Login. / Loginpage()

   Future loginWithEmailAndPasswords(String email, String password,BuildContext context) async {
        try {
    
          UserCredential register = await _firebaseAuth.signInWithEmailAndPassword(
              email: email, password: password);
          User registredUser = register.user;
          final ownerSnapshots= await ownerReference.doc(registredUser.uid).get();
          final userSnapshots= await  userSnapshot.doc(registredUser.uid).get();
    
          if(ownerSnapshots.exists){
    Navigator.of(context).pushReplacement(
      MaterialPageRoute(builder: (context)=>homecontroller(
        controllUserType:ownerSnapshots.data()['Account type'].toString(),
        userid: ownerSnapshots.data()['userId'].toString(),
    
      )));
         }else if(userSnapshots.exists){
    
           Navigator.of(context).pushReplacement(
              MaterialPageRoute(builder: (context)=>homecontroller(
                   controllUserType:userSnapshots.data()['Account type'].toString(),
                   userid: userSnapshots.data()['userId'].toString(),
    
                 )));
    
           } else{
             return null;
           }
        }
        on FirebaseAuthException catch (e) {
        if (e.code == 'user-not-found') {
        print('No user found for that email.');
        } else if (e.code == 'wrong-password') {
        print('Wrong password provided for that user.');
        }
        }
      }

Here is My HomeController Page.

    class homecontroller extends StatelessWidget {
      final String controllUserType;
      final String userid;
       const homecontroller({Key key,@required this.controllUserType,@required this.userid}):super(key: key);
      @override
      Widget build(BuildContext context) {
  Authservice auth
        final Authservice auth=Provider.of(context).auth;
        return StreamBuilder(
              stream:auth.authStateChanges,
              builder: (context,AsyncSnapshot<String>snapshot){
              if(snapshot.connectionState==ConnectionState.active){
                final bool SignedIn=snapshot.hasData;
                return SignedIn?HomePage(UserType:controllUserType,userID: userid,):firstview();
              }else{
                return CircularProgressIndicator();
              }
              },
        );
      }
    }

 finally Here is My home page()
    
    class HomePage extends StatefulWidget {
      final String UserType;
      final String userID;
    
      const HomePage({Key key,@required this.UserType,@required this.userID}):super(key: key);
      @override
      _HomePageState createState() => _HomePageState();
    }
    class _HomePageState extends State<HomePage> {
      DateTime backButtunPressedtime;
      bool isSignedIn= false;
      int _CurrentIndex=0;
      String owneruerID;
      dynamic uploadusertypes;
      List<Widget>_children;
      void initState(){
        super.initState();
        uploadusertypes= widget.UserType;
        owneruerID = widget.userID;
        _children=[
          TimeLinePage(),
          SearchPage(), //search(),
          UploadPage(UserSID:owneruerID,uploadusertypes:uploadusertypes),
          NotificationsPage(),
          ProfilePage(userProfileID:widget.userID),
        ];
       
        if(FirebaseAuth.instance.currentUser!=null){
            setState(() {
              isSignedIn= true;
            });
          }else{
            setState(() {
              isSignedIn= false;
               });
          }
    
      }
    
      @override
      Widget build(BuildContext context) {
      if(isSignedIn){
     if(widget.UserType== 'Customer'){
     return Scaffold(
       body: WillPopScope(
         onWillPop: onwillpops,
         child: buildHomeScreen(),
       ),
     );
         }
      else{
   return Scaffold(
       body: WillPopScope(
         onWillPop: onwillpops,
         child:buildSignedInScreen(),
       ),
    
      }return Container(
        height: 0.0,
        width: 0.0,
      );
      }
    Scaffold buildSignedInScreen(){
        return Scaffold(
          backgroundColor: Colors.white70,
          body: _agentchildren[_agentCurrentIndex],
    
          bottomNavigationBar: CupertinoTabBar(
            currentIndex: _agentCurrentIndex,
            backgroundColor: Colors.black,
            onTap: agentonTabchangePage,
            activeColor: Colors.green,
            inactiveColor: Colors.white10,
            items: [
              BottomNavigationBarItem(icon:Icon(Icons.home),title: Text('home'),),
              BottomNavigationBarItem(icon:Icon(Icons.search)),
              BottomNavigationBarItem(icon:Icon(Icons.notifications)),
              BottomNavigationBarItem(icon:Icon(Icons.person_add_alt_1_sharp)),
            ],
          ),
        );
      }
        Scaffold buildHomeScreen(){
            return Scaffold(
              backgroundColor: Colors.black,
              body: _children[_CurrentIndex],
              bottomNavigationBar: CupertinoTabBar(
                currentIndex: _CurrentIndex,
                backgroundColor: Colors.black,
                onTap: onTabchangePage,
                activeColor: Colors.green,
                inactiveColor: Colors.white,
                items: [
                  BottomNavigationBarItem(icon:Icon(Icons.home),title: Text('home'),),
                  BottomNavigationBarItem(icon:Icon(Icons.search)),
                  BottomNavigationBarItem(icon:Icon(Icons.photo_camera,size: 40,)),
                  BottomNavigationBarItem(icon:Icon(Icons.notifications)),
                  BottomNavigationBarItem(icon:Icon(Icons.person_add_alt_1_sharp)),
                ],
              ),
            );
        }
    
      void onTabchangePage(int index) {
        setState(() {
          _CurrentIndex=  index;
        });
    
      }
    
      Future<bool> onwillpops()async {
        DateTime curentTime= DateTime.now();
        //if backbutton is not pressed or toast mesge closed
        bool bckbutton= backButtunPressedtime==null||curentTime.difference(backButtunPressedtime)>Duration(seconds: 3);
        if(bckbutton){
          backButtunPressedtime= curentTime;
          Fluttertoast.showToast(
              msg: "Double Click to exit app",
            backgroundColor: Colors.black,
            textColor: Colors.white,
          );
          return false;
        }
       return true;
      }
    
    }

这是发生在我身上的问题。在我的主页中,我使用 WillPopScope 来处理设备后退按钮,当我使用设备后退按钮关闭应用程序时,应用程序按预期退出或关闭,但当再次重新打开时,显示第一个白屏页面并在 3 或 4 秒后显示第二个黑屏页面,并停留在该黑屏页面或应用程序崩溃

标签: flutterdart

解决方案


如果您使用命名路由并且您的路由名称以 开头/,则初始路由必须是"/"only。否则,请勿/在路线名称中使用。

另外,不要对命名路由进行硬编码,您可能会拼错它。相反,将其保存在常量文件中。


推荐阅读