Search code examples
c#xamarinxamarin.formsxamarin.androidxamarin.ios

Setting 2 second delay not working in xamarin


I am displaying 2 second fading animation in view class, after 2-secs, I want to go to viewmodel class to run which load login page or signup page logic

right now its skipping 2 sec animation and going directly to viewmodel. idk what the issue is here

if i delete line BindingContext = new SplashscreenViewModel(); than animation shows up but it doesnt go to viewmodel class

SplashscreenPage.xaml.cs - view class

    public SplashscreenPage ()
    {
        InitializeComponent ();
        Animation();
        BindingContext = new SplashscreenViewModel();
    }

    async void Animation()
    {
        ssImage.Opacity = 0;
        await Task.WhenAll(
            ssImage.FadeTo(1, 2000),
            ssImage.ScaleTo(1.1, 2000)
            );
    }//end of method

Splashscreen - viewmodel class

 public SplashscreenViewModel()
        {
            WhichPageToLoad();
        }
 
  async void WhichPageToLoad()
    {

            var getToken = await SecureStorage.GetAsync("Save_Pin_1");
            if(getToken == null)
            {
                var route = $"{ nameof(SignupPage)}";
                await Shell.Current.GoToAsync(route);
            }
            else
            {
                var route = $"{ nameof(LoginPage)}";
                await Shell.Current.GoToAsync(route);
            }
}

Solution

  • there is really no point in having a VM class or assigning the BindingContext since you are not doing any databinding. You can just call the navigation code after the animation completes. You cannot make async calls from the constructor, so moving the animation and navigation login into OnAppearing will allow you to make an async call

    public SplashscreenPage ()
    {
        InitializeComponent ();
    }
    
    async override void OnAppearing()
    {
        ssImage.Opacity = 0;
    
        await Task.WhenAll(
            ssImage.FadeTo(1, 2000),
            ssImage.ScaleTo(1.1, 2000)
            );
    
        var getToken = await SecureStorage.GetAsync("Save_Pin_1");
          
        if(getToken == null)
            {
                var route = $"{ nameof(SignupPage)}";
                await Shell.Current.GoToAsync(route);
            }
            else
            {
                var route = $"{ nameof(LoginPage)}";
                await Shell.Current.GoToAsync(route);
            }
    }