错误:预期类型的​​值' String',但获得了类型之一。 (在颤音中)

发布于 2025-02-11 15:11:28 字数 10435 浏览 1 评论 0原文

我正在尝试使用nodejs和mongodb在flutter应用程序(具有登录页面和注册页面)中对用户的登录信息进行身份验证,但是每当我输入有效的用户并按下登录按钮时,我会收到以下错误:

    Launching lib\main.dart on Chrome in debug mode...
This app is linked to the debug service: ws://127.0.0.1:50690/e09XNGpEkmc=/ws
Debug service listening on ws://127.0.0.1:50690/e09XNGpEkmc=/ws
 Running with sound null safety
Connecting to VM Service at ws://127.0.0.1:50690/e09XNGpEkmc=/ws
Flutter Web Bootstrap: Auto
All validations passed
Error: Expected a value of type 'String', but got one of type 'Null'
    at Object.throw_ [as throw] (http://localhost:50635/dart_sdk.js:5080:11)
    at Object.castError (http://localhost:50635/dart_sdk.js:5039:15)
    at Object.cast [as as] (http://localhost:50635/dart_sdk.js:5356:17)
    at String.as (http://localhost:50635/dart_sdk.js:46240:19)
at authservice.AuthService.new.login (http://localhost:50635/packages/flutterform/authservice.dart.lib.js:39:67)
    at login.throw (<anonymous>)
    at http://localhost:50635/dart_sdk.js:40646:38
    at _RootZone.runBinary (http://localhost:50635/dart_sdk.js:40515:59)
    at _FutureListener.thenAwait.handleError (http://localhost:50635/dart_sdk.js:35449:33)
    at handleError (http://localhost:50635/dart_sdk.js:36015:51)
    at _Future._propagateToListeners (http://localhost:50635/dart_sdk.js:36041:17)
    at [_completeError] (http://localhost:50635/dart_sdk.js:35878:23)
    at [_completeError] (http://localhost:50635/dart_sdk.js:35358:36)
    at _SyncCompleter.new.completeError (http://localhost:50635/dart_sdk.js:35282:29)
    at onError (http://localhost:50635/dart_sdk.js:35122:49)
    at _RootZone.runBinary (http://localhost:50635/dart_sdk.js:40515:59)
    at _FutureListener.then.handleError (http://localhost:50635/dart_sdk.js:35449:33)
    at handleError (http://localhost:50635/dart_sdk.js:36015:51)
    at _Future._propagateToListeners (http://localhost:50635/dart_sdk.js:36041:17)
    at [_completeError] (http://localhost:50635/dart_sdk.js:35878:23)
    at async._AsyncCallbackEntry.new.callback (http://localhost:50635/dart_sdk.js:35927:31)
    at Object._microtaskLoop (http://localhost:50635/dart_sdk.js:40778:13)
    at _startMicrotaskLoop (http://localhost:50635/dart_sdk.js:40784:13)
    at http://localhost:50635/dart_sdk.js:36261:9
Application finished.
Exited (sigterm)

我正在运行代码。在VSCODE编辑器中,我的服务器正在Heroku运行。 以下是我的代码:

从main.dart:

import 'package:flutter/material.dart';
import '../../signup.dart';
import '../../login.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of our application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Application name
      title: 'Registration Form',
      // Application theme data, we can set the colors for the application as
      // you want
      theme: ThemeData(
        primarySwatch: Colors.orange,
      ),
      home: MySignUpPage(),
      routes: {
        'register': (context) => MySignUpPage(),
        'login': (context) => MyLoginPage(),
      },
    );
  }
}

from Login.dart:

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../../authservice.dart';

class MyLoginPage extends StatefulWidget {
  @override
  LoginForm createState() {
    return LoginForm();
  }
}

class LoginForm extends State<MyLoginPage> {
  final formKey = GlobalKey<FormState>();
  final passwordController = TextEditingController();
  final confirmpasswordController = TextEditingController();
  var name, password, token;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // The title text which will be shown on the action bar
        title: Text('Registration'),
      ),
      body: Container(
        padding: EdgeInsets.symmetric(
          vertical: 50.0,
          horizontal: 10.0,
        ),
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage("images/signupimg.jpg"),
            fit: BoxFit.cover,
          ),
        ),
        child: Form(
          key: formKey,
          child: Column(
            children: <Widget>[
              Container(
                  margin: EdgeInsets.all(2),
                  padding: const EdgeInsets.all(8.0),
                  child: const Align(
                      alignment: Alignment.topLeft,
                      child: Text(
                        'Login',
                        style: TextStyle(
                          fontSize: 40,
                          fontWeight: FontWeight.bold,
                        ),
                        textAlign: TextAlign.left,
                      ))),
              Container(
                margin: EdgeInsets.all(2),
                padding: const EdgeInsets.all(8.0),
                child: TextFormField(
                  autovalidateMode: AutovalidateMode.onUserInteraction,
                  validator: (String? val) {
                    if (val == null || val.isEmpty) {
                      return 'Username cannot be empty';
                    } else {
                      name = val;
                    }
                    return null;
                  },
                  decoration: InputDecoration(
                      filled: true, //<-- SEE HERE
                      fillColor: Colors.white,
                      labelText: 'Username',
                      hintText: 'Your Username',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(20.0),
                      )),
                ),
              ),
              Container(
                margin: EdgeInsets.all(2),
                padding: const EdgeInsets.all(8.0),
                child: TextFormField(
                  obscureText: true,
                  controller: passwordController,
                  autovalidateMode: AutovalidateMode.onUserInteraction,
                  validator: (String? val) {
                    if (val == null || val.isEmpty) {
                      return 'Password cannot be empty';
                    } else if (val.length < 6) {
                      return 'Password must be at least 6 characters long.';
                    } else {
                      password = val;
                    }
                    return null;
                  },
                  decoration: InputDecoration(
                      filled: true, //<-- SEE HERE
                      fillColor: Colors.white,
                      labelText: 'Password',
                      hintText: 'Your password',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(20.0),
                      )),
                ),
              ),
              Container(
                margin: EdgeInsets.all(10),
                padding: EdgeInsets.all(10),
                child: ElevatedButton(
                  child: Text(
                    "Login",
                    style: TextStyle(fontSize: 20),
                  ),
                  onPressed: () {
                    AuthService().login(name, password).then((val) {
                      if (val.data['success'] != null) {
                        token = val.data!['token'];
                        Fluttertoast.showToast(
                          msg: 'Authenticated',
                          toastLength: Toast.LENGTH_SHORT,
                          gravity: ToastGravity.BOTTOM,
                          backgroundColor: Colors.white,
                          textColor: Colors.white,
                          fontSize: 16.0,
                        );
                      }
                    });
                    if (formKey.currentState!.validate()) {
                      debugPrint('All validations passed');
                    }
                    style:
                    ElevatedButton.styleFrom(
                      primary: Colors.orange, // Background color
                      onPrimary: Colors.black, //Text Color (Foreground color)
                      elevation: 3, //elevation of button
                      shape: RoundedRectangleBorder(
                          //to set border radius to button
                          borderRadius: BorderRadius.circular(35)),
                    );
                  },
                ),
              ),
              Container(
                margin: EdgeInsets.all(10),
                child: Text(
                  "Don't have an account?",
                  style: TextStyle(fontSize: 16),
                ),
              ),
              Container(
                  child: TextButton(
                      onPressed: () {
                        Navigator.pushNamed(context, 'register');
                      },
                      child: Text("Sign up",
                          style: TextStyle(
                            decoration: TextDecoration.underline,
                            fontSize: 18,
                            color: Colors.orange,
                          ))))
            ],
          ),
        ),
      ),
    );
  }
}

from Authservice.dart 我的服务器):

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:fluttertoast/fluttertoast.dart';

class AuthService {
  Dio dio = new Dio();
  login(String name, String password) async {
    try {
      return await dio.post(
          'https://flutter-collegeapp.herokuapp.com/authenticate',
          data: {"name": name, "password": password},
          options: Options(contentType: Headers.formUrlEncodedContentType));
    } on DioError catch (e) {
      Fluttertoast.showToast(
        msg: (e.response?.data['msg']),
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        backgroundColor: Colors.white,
        textColor: Colors.orange[900],
        fontSize: 16.0,
      );
    }
  }
}

我遵循了本YouTube教程来编写此代码(由于Flutter中的新更新而进行了一些更改)

https://www.youtube.com/watch?v=2d_76lkyf1c&; t = 4903S

有人可以告诉我有什么问题,为什么发生此错误?

I am trying to authenticate a user's login info in a flutter app (having a login page and signup page) using nodeJS and MongoDB, but whenever I enter a valid user and press login button, I get the following error:

    Launching lib\main.dart on Chrome in debug mode...
This app is linked to the debug service: ws://127.0.0.1:50690/e09XNGpEkmc=/ws
Debug service listening on ws://127.0.0.1:50690/e09XNGpEkmc=/ws
 Running with sound null safety
Connecting to VM Service at ws://127.0.0.1:50690/e09XNGpEkmc=/ws
Flutter Web Bootstrap: Auto
All validations passed
Error: Expected a value of type 'String', but got one of type 'Null'
    at Object.throw_ [as throw] (http://localhost:50635/dart_sdk.js:5080:11)
    at Object.castError (http://localhost:50635/dart_sdk.js:5039:15)
    at Object.cast [as as] (http://localhost:50635/dart_sdk.js:5356:17)
    at String.as (http://localhost:50635/dart_sdk.js:46240:19)
at authservice.AuthService.new.login (http://localhost:50635/packages/flutterform/authservice.dart.lib.js:39:67)
    at login.throw (<anonymous>)
    at http://localhost:50635/dart_sdk.js:40646:38
    at _RootZone.runBinary (http://localhost:50635/dart_sdk.js:40515:59)
    at _FutureListener.thenAwait.handleError (http://localhost:50635/dart_sdk.js:35449:33)
    at handleError (http://localhost:50635/dart_sdk.js:36015:51)
    at _Future._propagateToListeners (http://localhost:50635/dart_sdk.js:36041:17)
    at [_completeError] (http://localhost:50635/dart_sdk.js:35878:23)
    at [_completeError] (http://localhost:50635/dart_sdk.js:35358:36)
    at _SyncCompleter.new.completeError (http://localhost:50635/dart_sdk.js:35282:29)
    at onError (http://localhost:50635/dart_sdk.js:35122:49)
    at _RootZone.runBinary (http://localhost:50635/dart_sdk.js:40515:59)
    at _FutureListener.then.handleError (http://localhost:50635/dart_sdk.js:35449:33)
    at handleError (http://localhost:50635/dart_sdk.js:36015:51)
    at _Future._propagateToListeners (http://localhost:50635/dart_sdk.js:36041:17)
    at [_completeError] (http://localhost:50635/dart_sdk.js:35878:23)
    at async._AsyncCallbackEntry.new.callback (http://localhost:50635/dart_sdk.js:35927:31)
    at Object._microtaskLoop (http://localhost:50635/dart_sdk.js:40778:13)
    at _startMicrotaskLoop (http://localhost:50635/dart_sdk.js:40784:13)
    at http://localhost:50635/dart_sdk.js:36261:9
Application finished.
Exited (sigterm)

I am running the code in VSCode editor and my server is running in Heroku.
Here are my codes:

From main.dart:

import 'package:flutter/material.dart';
import '../../signup.dart';
import '../../login.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of our application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Application name
      title: 'Registration Form',
      // Application theme data, we can set the colors for the application as
      // you want
      theme: ThemeData(
        primarySwatch: Colors.orange,
      ),
      home: MySignUpPage(),
      routes: {
        'register': (context) => MySignUpPage(),
        'login': (context) => MyLoginPage(),
      },
    );
  }
}

From login.dart:

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../../authservice.dart';

class MyLoginPage extends StatefulWidget {
  @override
  LoginForm createState() {
    return LoginForm();
  }
}

class LoginForm extends State<MyLoginPage> {
  final formKey = GlobalKey<FormState>();
  final passwordController = TextEditingController();
  final confirmpasswordController = TextEditingController();
  var name, password, token;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // The title text which will be shown on the action bar
        title: Text('Registration'),
      ),
      body: Container(
        padding: EdgeInsets.symmetric(
          vertical: 50.0,
          horizontal: 10.0,
        ),
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage("images/signupimg.jpg"),
            fit: BoxFit.cover,
          ),
        ),
        child: Form(
          key: formKey,
          child: Column(
            children: <Widget>[
              Container(
                  margin: EdgeInsets.all(2),
                  padding: const EdgeInsets.all(8.0),
                  child: const Align(
                      alignment: Alignment.topLeft,
                      child: Text(
                        'Login',
                        style: TextStyle(
                          fontSize: 40,
                          fontWeight: FontWeight.bold,
                        ),
                        textAlign: TextAlign.left,
                      ))),
              Container(
                margin: EdgeInsets.all(2),
                padding: const EdgeInsets.all(8.0),
                child: TextFormField(
                  autovalidateMode: AutovalidateMode.onUserInteraction,
                  validator: (String? val) {
                    if (val == null || val.isEmpty) {
                      return 'Username cannot be empty';
                    } else {
                      name = val;
                    }
                    return null;
                  },
                  decoration: InputDecoration(
                      filled: true, //<-- SEE HERE
                      fillColor: Colors.white,
                      labelText: 'Username',
                      hintText: 'Your Username',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(20.0),
                      )),
                ),
              ),
              Container(
                margin: EdgeInsets.all(2),
                padding: const EdgeInsets.all(8.0),
                child: TextFormField(
                  obscureText: true,
                  controller: passwordController,
                  autovalidateMode: AutovalidateMode.onUserInteraction,
                  validator: (String? val) {
                    if (val == null || val.isEmpty) {
                      return 'Password cannot be empty';
                    } else if (val.length < 6) {
                      return 'Password must be at least 6 characters long.';
                    } else {
                      password = val;
                    }
                    return null;
                  },
                  decoration: InputDecoration(
                      filled: true, //<-- SEE HERE
                      fillColor: Colors.white,
                      labelText: 'Password',
                      hintText: 'Your password',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(20.0),
                      )),
                ),
              ),
              Container(
                margin: EdgeInsets.all(10),
                padding: EdgeInsets.all(10),
                child: ElevatedButton(
                  child: Text(
                    "Login",
                    style: TextStyle(fontSize: 20),
                  ),
                  onPressed: () {
                    AuthService().login(name, password).then((val) {
                      if (val.data['success'] != null) {
                        token = val.data!['token'];
                        Fluttertoast.showToast(
                          msg: 'Authenticated',
                          toastLength: Toast.LENGTH_SHORT,
                          gravity: ToastGravity.BOTTOM,
                          backgroundColor: Colors.white,
                          textColor: Colors.white,
                          fontSize: 16.0,
                        );
                      }
                    });
                    if (formKey.currentState!.validate()) {
                      debugPrint('All validations passed');
                    }
                    style:
                    ElevatedButton.styleFrom(
                      primary: Colors.orange, // Background color
                      onPrimary: Colors.black, //Text Color (Foreground color)
                      elevation: 3, //elevation of button
                      shape: RoundedRectangleBorder(
                          //to set border radius to button
                          borderRadius: BorderRadius.circular(35)),
                    );
                  },
                ),
              ),
              Container(
                margin: EdgeInsets.all(10),
                child: Text(
                  "Don't have an account?",
                  style: TextStyle(fontSize: 16),
                ),
              ),
              Container(
                  child: TextButton(
                      onPressed: () {
                        Navigator.pushNamed(context, 'register');
                      },
                      child: Text("Sign up",
                          style: TextStyle(
                            decoration: TextDecoration.underline,
                            fontSize: 18,
                            color: Colors.orange,
                          ))))
            ],
          ),
        ),
      ),
    );
  }
}

From authservice.dart (which holds the login function and connection details to my server):

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:fluttertoast/fluttertoast.dart';

class AuthService {
  Dio dio = new Dio();
  login(String name, String password) async {
    try {
      return await dio.post(
          'https://flutter-collegeapp.herokuapp.com/authenticate',
          data: {"name": name, "password": password},
          options: Options(contentType: Headers.formUrlEncodedContentType));
    } on DioError catch (e) {
      Fluttertoast.showToast(
        msg: (e.response?.data['msg']),
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        backgroundColor: Colors.white,
        textColor: Colors.orange[900],
        fontSize: 16.0,
      );
    }
  }
}

I have followed this youtube tutorial to write this code (have made some changes due to new updates in flutter)

https://www.youtube.com/watch?v=2D_76lkyF1c&t=4903s

Can someone please tell me what is wrong and why this error is occuring?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文