Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Navigation in flutter without context

Tags:

flutter

dart

I created a service folder and made a file in it called request. dart, here I intend to place all requests I make into a class called AuthService, with the login request below I want to be able to navigate to the home screen once response.statusCode == 200 or 201 but I am unable to do that because navigation requires a context and my class is neither a Stateful nor Stateless widget, is there any way I can navigate without the context??

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/material.dart';

class AuthService {

  login(email, password) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();

    if (email == "" && password == "") {
      return;
    }

    try {
      Map data = {'email': email, 'password': password};

      var jsonResponse;
      var response = await http
          .post('https://imyLink.com/authenticate', body: data);
      if (response.statusCode == 200 || response.statusCode == 201) {

//I want to navigate to my home screen once the request made is successful

        jsonResponse = json.decode(response.body);
        if (jsonResponse != null) {
          await sharedPreferences.setString("userToken", jsonResponse["token"]);
          var token = sharedPreferences.getString("userToken");
          print('Token: $token');
          print(jsonResponse);
          print("Login successful");
        }
      } else {
        print(response.statusCode);
        print('Login Unsuccessful');
        print(response.body);
      }
    } catch (e) {
      print(e);
    }
}
like image 222
Zaza.codes Avatar asked Aug 09 '20 08:08

Zaza.codes


People also ask

How do I use navigation without context in Flutter?

In the main file, we then pass our GlobalKey as the NavigatorKey to our MaterialApp . We'll have two basic views just to show the navigation. And then finally we can go ahead and navigate using the NavigationService in the FloatingActionButton on the HomeView. That's it.

How would perform navigation without using the BuildContext?

We'll start by adding an optional dynamic parameter to the navigateTo function in the NavigationService and passing that to our pushNamed call. Now in the LoginViewModel where we navigate we'll pass in a argument of type String to show in the HomeView on the Button. _navigationService.

What is navigatorKey in Flutter?

navigatorKey property Null safetyA key to use when building the Navigator. If a navigatorKey is specified, the Navigator can be directly manipulated without first obtaining it from a BuildContext via Navigator. of: from the navigatorKey, use the GlobalKey. currentState getter.


1 Answers

First, create a class

import 'package:flutter/material.dart';

class NavigationService{
  GlobalKey<NavigatorState> navigationKey;

  static NavigationService instance = NavigationService();

   NavigationService(){
     navigationKey = GlobalKey<NavigatorState>();
   }

  Future<dynamic> navigateToReplacement(String _rn){
return navigationKey.currentState.pushReplacementNamed(_rn);
  }
 Future<dynamic> navigateTo(String _rn){
   return navigationKey.currentState.pushNamed(_rn);
  }
 Future<dynamic> navigateToRoute(MaterialPageRoute _rn){
   return navigationKey.currentState.push(_rn);
  }

 goback(){
   return navigationKey.currentState.pop();

  }
  }

In your main.dart file.

 MaterialApp(
  navigatorKey: NavigationService.instance.navigationKey,
  initialRoute: "login",
  routes: {
    "login":(BuildContext context) =>Login(),
    "register":(BuildContext context) =>Register(),
    "home":(BuildContext context) => Home(),

  },
);

Then you can call the function from anywhere in your project like...

 NavigationService.instance.navigateToReplacement("home");
 NavigationService.instance.navigateTo("home");
like image 157
S.R Keshav Avatar answered Sep 28 '22 09:09

S.R Keshav