dart 获取Flutter错误未定义的名称上下文

yhuiod9q  于 2023-11-14  发布在  Flutter
关注(0)|答案(3)|浏览(116)

这是我的代码。我得到错误,它告诉上下文不能为空:


的数据



我已经尝试了所有的谷歌方法,但它仍然存在,我只是试图创建简单的登录系统与节点和Flutter,而我得到这个错误。

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());
    }
  }
  }
fiei3ece

fiei3ece1#

您必须将小部件的BuildContext传递给registerUser函数才能使用它:

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

字符串
在访问它的时候,下面是:

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


当使用await关键字执行异步任务时,请确保在使用它的上下文之前检查小部件是否仍然被挂载:

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());
    }

7rfyedvj

7rfyedvj2#

在Stateless widgets中,BuildContext不是全局访问的。
你可以通过在registerUser函数中传递上下文来实现这一点,如下所示:

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

字符串
然后在调用位置传递上下文

CustomButton(
              onTap: registerUser(context),
            ),

67up9zun

67up9zun3#

在声明的方法**registerUser()**中找不到上下文,只能在Widget构建方法中访问上下文

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

字符串
这不是问题,但解决方案是将BuildContext类型的上下文作为registerUser方法中的参数,然后在Widget树中调用该方法时传递此上下文:

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


然后在调用registerUser时,从小部件树传递上下文,

registerUser(context: context)


我建议你多学习widget树,多了解方法中的参数和参数用法

相关问题