skip to Main Content

This is my code. I am getting error, it’s telling context can not be empty:

Image

Image

I have already tried all Google methods but its still there I am just trying to create simple login system with Node and Flutter while I am getting this error.

import 'package:flutter/material.dart';
import 'package:the_kitchen/common/custom_button.dart';
import 'package:the_kitchen/common/custom_textinput.dart';
import 'package:the_kitchen/constants/global_variables.dart';
import 'package:the_kitchen/service/auth_service.dart';

class RegisterPage extends StatelessWidget {
  
  RegisterPage({super.key});
  

  final userNameController = TextEditingController();
  final emailController = TextEditingController();
  final passwordController = TextEditingController();

  final AuthService authService = AuthService();

  

  void registerUser() {
    authService.registerUser(
      context: context,
      userName: userNameController.text,
      email: emailController.text,
      password: passwordController.text,
      
    );
  }


  @override
  
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: GlobalVariables.backgroundColor,
      body: SafeArea(
        child: Center(
          child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
            const SizedBox(
              height: 0,
            ),

            //logo
            Center(
              child: Image.asset('lib/images/thekitchenlogo.png'),
            ),

            //welcomeback
            const Text(
              "Welcome Back You've been missed!",
              style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: GlobalVariables.unselectedNavBarColor),
            ),

            const SizedBox(
              height: 25,
            ),

            CustomTextFiled(
              controller: userNameController,
              hintText: "Username",
              obscureText: false,
            ),

            const SizedBox(
              height: 10,
            ),

            CustomTextFiled(
              controller: emailController,
              hintText: "Email",
              obscureText: false,
            ),

            const SizedBox(
              height: 10,
            ),

            CustomTextFiled(
              controller: passwordController,
              hintText: "Password",
              obscureText: true,
            ),

            const SizedBox(
              height: 25,
            ),


            CustomButton(
              onTap: registerUser,
            ),

            const SizedBox(
              height: 25,
            ),

            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Text('Member?'),
                const SizedBox(
                  width: 4,
                ),
                TextButton(
                    onPressed: () => Navigator.pushNamed(context, '/login'),
                    child: const Text(
                      'Login Now',
                      style: TextStyle(
                          color: GlobalVariables.secondaryColor,
                          fontWeight: FontWeight.bold),
                    ))
              ],
            )
          ]),
        ),
      ),
    );
  }
}


import 'dart:io';

import 'package:flutter/material.dart';
import 'package:the_kitchen/constants/global_variables.dart';
import 'package:the_kitchen/models/user.dart';
import 'package:http/http.dart' as http;
import 'package:the_kitchen/utils/utils.dart';


class AuthService {
  void registerUser(String text, {
    required BuildContext context,
    required String userName,
    required String email,
    required String password,
  }) async{
    try{
      User user = User(
        userName: userName,
        email: email,
        password: password,
        id: '',
        token: '',
      );

      http.Response res = await http.post(
        Uri.parse('${GlobalVariables.uri}/api/register'),
        body: user.toJson(),
        headers: <String, String>{
          'Content-Type': 'application/json; charset=UTF-8',
        },
      );

         httpErrorHandle(
        response: res,
        context: context,
        onSuccess: () {
          showSnackBar(
            context,
            'Account created! Login with the same credentials!',
          );
        },
      );
    } catch (e) {
      showSnackBar(context, e.toString());
    }
  }
  }

3

Answers


  1. You have to pass the widget’s BuildContext to the registerUser function in order to use it:

    void registerUser(BuildContext context) {
        authService.registerUser(
          context: context,
          userName: userNameController.text,
          email: emailController.text,
          password: passwordController.text,
          
        );
      }
    

    Down below when accessing it:

    CustomButton(
      onTap: () => registerUser(context),
    ),
    

    And when using the await keyword to perform asynchronous tasks, make sure to check if the widget is still mounted before using it’s context:

    try{
          User user = User(
            userName: userName,
            email: email,
            password: password,
            id: '',
            token: '',
          );
    
          http.Response res = await http.post(
            Uri.parse('${GlobalVariables.uri}/api/register'),
            body: user.toJson(),
            headers: <String, String>{
              'Content-Type': 'application/json; charset=UTF-8',
            },
          );
    
          if (!context.mounted) return;
    
             httpErrorHandle(
            response: res,
            context: context,
            onSuccess: () {
              showSnackBar(
                context,
                'Account created! Login with the same credentials!',
              );
            },
          );
        } catch (e) {
          if (!context.mounted) return;
          showSnackBar(context, e.toString());
        }
    
    Login or Signup to reply.
  2. In Stateless widgets BuildContext is not accessed globally.

    you can achieve this by passing context in registerUser function like this:

    void registerUser(BuildContext context) {
        authService.registerUser(
          context: context,
          userName: userNameController.text,
          email: emailController.text,
          password: passwordController.text,
          
        );
      }
    

    Then passing context in calling place

    CustomButton(
                  onTap: registerUser(context),
                ),
    
    Login or Signup to reply.
  3. No context is found in the declared method registerUser().
    Context can only be accessed in the Widget build method

    void registerUser() {
        authService.registerUser(
          context: context,
          userName: userNameController.text,
          email: emailController.text,
          password: passwordController.text,
          
        );
      }
    

    This is not an issue, but a solution will be to make context of type BuildContext a parameter in registerUser method, then pass this context when the method is called in the Widget tree as:

       void registerUser({required BuildContext context}) {
            authService.registerUser(
              context: context,
              userName: userNameController.text,
              email: emailController.text,
              password: passwordController.text,
              
            );
          }
    

    Then on call of registerUser, pass the context from the widget tree as

    registerUser(context: context)
    

    I would suggest you study more on widget tree and understand more of argument and parameter usage in a method

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search