Xamarin Forms: How do you Navigate to a New View Immediately After the Previous View Loads Using ViewModels

Nicholas R 1 Reputation point
2021-03-16T21:31:21.713+00:00

In my app, users have to login the first time, but a token is generated to allow them to skip the login process on subsequent logins. The login page checks that the token is correct in its viewmodel constructor, calling Shell.Current.GoToAsync() if it is. This does not work as it should, as the login page was not completely loaded when the new page was pushed, and will load on top of the new page. I have tried the workaround in this question, but that does not work either. Here's a part of the code:

        public LoginPageViewModel()
        {
            userData = (Application.Current as App).userData;
            SendLogin = new Command(Login);
            TokenLogin();
        }

        //Attempts to login via token
        private async void TokenLogin()
        {
            string user = Tokenizer.GetTokenUser();
            string token = Tokenizer.GetToken();
            if(userData.TokenLogin(user, token))
            {
                await Shell.Current.GoToAsync(nameof(CategoryPage));//Login successful
            }
        }
Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,296 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. StephenH 86 Reputation points
    2021-03-16T23:48:53.497+00:00

    Look for the token on startup and then don't even go to the login window, go directly to the "second form"
    FYI, if you are storing a "token" make sure you are using secure storage
    https://learn.microsoft.com/en-us/xamarin/essentials/secure-storage?context=xamarin%2Fandroid&tabs=ios

    0 comments No comments

  2. Cole Xia (Shanghai Wicresoft Co,.Ltd.) 6,751 Reputation points
    2021-03-17T07:30:18.637+00:00

    Hello,

    Welcome to Microsoft Q&A!

    The better way is that set LoginPage as MainPage at first ,and then change App.Current.MainPage upon login successfully .

    App

       MainPage =  new LoginPage();  
    

    LoginPageViewModel

       private async void TokenLogin()  
                {  
                    string user = Tokenizer.GetTokenUser();  
                    string token = Tokenizer.GetToken();  
                    if(userData.TokenLogin(user, token))  
                    {  
                        App.Current.MainPage = new AppShell();  
                    }  
                }  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments