当前位置: 首页 > 知识库问答 >
问题:

未处理的异常:类型“List”不是类型“String”的子类型

宗政卓
2023-03-14

我正在开发我的flutter应用程序的身份验证。请帮我解决这个问题。我无法识别返回这样一个错误的问题,声明未处理异常:类型列表不是类型字符串的子类型。

以下是登录屏幕的代码:

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

class WelcomeBackPage extends StatefulWidget {
  @override
  WelcomeBackPageState createState() => WelcomeBackPageState();
}

class WelcomeBackPageState extends State<WelcomeBackPage> {
  final _scaffoldKey = GlobalKey<ScaffoldState>();
  final _formKey = GlobalKey<FormState>();
  bool _isSubmitting, _obscureText = true;
  String _email, _password;

  Widget _showHello() {
    return Text(
      'Hello',
      style: GoogleFonts.montserrat(
          fontSize: 70.0,
          fontWeight: FontWeight.w800,
          textStyle: TextStyle(color: Colors.black)),
    );
  }

  Widget _showThere() {
    return Container(
        padding: EdgeInsets.only(left: 5.0),
        child: Text(
          'There',
          style: GoogleFonts.montserrat(
              fontSize: 70.0,
              fontWeight: FontWeight.w800,
              height: 0.7,
              textStyle: TextStyle(color: Colors.black)),
        ));
  }

  Widget _showDot() {
    return Text(
      '.',
      style: GoogleFonts.montserrat(
          fontSize: 70.0,
          fontWeight: FontWeight.bold,
          height: 0.7,
          textStyle: TextStyle(color: Colors.green)),
    );
  }

  Widget _showEmailInput() {
    return Padding(
        padding: EdgeInsets.only(top: 30.0, left: 5.0),
        child: TextFormField(
          onSaved: (val) => _email = val,
          decoration: InputDecoration(
            labelText: 'EMAIL',
            labelStyle: TextStyle(
                fontFamily: 'Montserrat',
                fontWeight: FontWeight.bold,
                color: Colors.grey),
            enabledBorder: UnderlineInputBorder(
              borderSide: BorderSide(color: Colors.grey[300]),
            ),
            focusedBorder: UnderlineInputBorder(
                borderSide: BorderSide(color: Colors.green)),
          ),
          keyboardType: TextInputType.emailAddress,
          validator: (val) => !val.contains('@') ? 'Invalid Email' : null,
        ));
  }

  Widget _showPasswordInput() {
    return Padding(
        padding: EdgeInsets.only(top: 10.0, left: 5.0),
        child: TextFormField(
          onSaved: (val) => _password = val,
          decoration: InputDecoration(
            suffixIcon: GestureDetector(
                onTap: () {
                  setState(() => _obscureText = !_obscureText);
                },
                child: Icon(
                    _obscureText ? Icons.visibility : Icons.visibility_off)),
            labelText: 'PASSWORD',
            labelStyle: TextStyle(
                fontFamily: 'Montserrat',
                fontWeight: FontWeight.bold,
                color: Colors.grey),
            enabledBorder: UnderlineInputBorder(
              borderSide: BorderSide(color: Colors.grey[300]),
            ),
            focusedBorder: UnderlineInputBorder(
                borderSide: BorderSide(color: Colors.green)),
          ),
          obscureText: _obscureText,
          validator: (val) => val.length < 6 ? 'Invalid Password' : null,
        ));
  }

  Widget _showForgotPassword() {
    return Container(
        alignment: Alignment(1.2, 0.0),
        child: Padding(
          padding: EdgeInsets.only(top: 0.0),
          child: Column(
            children: <Widget>[
              FlatButton(
                onPressed: () {},
                child: Text(
                  'Forgot Password',
                  style: GoogleFonts.montserrat(
                      color: Colors.green,
                      fontSize: 16.0,
                      fontWeight: FontWeight.bold,
                      decoration: TextDecoration.underline),
                ),
              ),
            ],
          ),
        ));
  }

  Widget _showLogin() {
    return Padding(
        padding: EdgeInsets.only(top: 20.0),
        child: ButtonTheme(
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(100)),
            child: Center(
                child: _isSubmitting == true
                    ? CircularProgressIndicator(
                        valueColor: AlwaysStoppedAnimation(Colors.green),
                      )
                    : RaisedButton(
                        onPressed: _login,
                        textColor: Colors.white,
                        color: Colors.green,
                        padding: EdgeInsets.all(5.0),
                        child: Container(
                          height: 50,
                          width: MediaQuery.of(context).size.width,
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(100),
                              color: Colors.green),
                          padding: const EdgeInsets.all(15.0),
                          child: Text(
                            'LOGIN',
                            textAlign: TextAlign.center,
                            style: GoogleFonts.montserrat(
                              letterSpacing: 2.0,
                              fontSize: 18.0,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                      ))));
  }

  void _login() {
    final form = _formKey.currentState;

    if (form.validate()) {
      form.save();
      _registerUser();
    }
  }

  void _registerUser() async {
    setState(() => _isSubmitting = true);
    http.Response response = await http.post(
        'http://192.168.43.9:1337/auth/local',
        body: {"identifier": _email, "password": _password});
    final responseData = json.decode(response.body);
    if (response.statusCode == 200) {
      setState(() => _isSubmitting = false);
      _showSuccessSnack();
      _redirectUser();
      print(responseData);
    } else {
      setState(() => _isSubmitting = false);
      final String errorMsg = responseData['message'];
      _showErrorSnack(errorMsg);
    }
  }

  void _showSuccessSnack() {
    final snackbar = SnackBar(
        content: Text(' User successfully logged in ',
            style:
                GoogleFonts.montserrat(color: Colors.green, fontSize: 16.0)));
    _scaffoldKey.currentState.showSnackBar(snackbar);
    _formKey.currentState.reset();
  }

  void _showErrorSnack(String errorMsg) {
    final snackbar = SnackBar(
        content: Text(errorMsg,
            style: GoogleFonts.montserrat(color: Colors.red, fontSize: 16.0)));
    _scaffoldKey.currentState.showSnackBar(snackbar);
    throw Exception('Error logging in: $errorMsg');
  }

  void _redirectUser() {
    Future.delayed(Duration(seconds: 2), () {
      Navigator.pushReplacementNamed(context, '/intro');
    });
  }

  Widget _showGoogle() {
    return Padding(
        padding: EdgeInsets.only(top: 20.0),
        child: OutlineButton(
          shape: StadiumBorder(),
          textColor: Colors.black,
          borderSide: BorderSide(
              color: Colors.black, style: BorderStyle.solid, width: 2.5),
          onPressed: () {},
          padding: EdgeInsets.all(5.0),
          child: Container(
            height: 50,
            width: MediaQuery.of(context).size.width,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Center(
                  child: ImageIcon(AssetImage('assets/facebook.png')),
                ),
                SizedBox(width: 10.0),
                Center(
                  child: Text(
                    'Log in with Google',
                    textAlign: TextAlign.center,
                    style: GoogleFonts.montserrat(
                      fontSize: 18.0,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                )
              ],
            ),
          ),
        ));
  }

  Widget _showNewRegister() {
    return Padding(
        padding: EdgeInsets.only(top: 35.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'New to Oristore ?',
              style: GoogleFonts.montserrat(
                fontSize: 16.0,
                fontWeight: FontWeight.w600,
              ),
            ),
            SizedBox(width: 5.0),
            InkWell(
              onTap: () => Navigator.pushReplacementNamed(context, '/register'),
              child: Text(
                'Register',
                style: GoogleFonts.montserrat(
                  fontSize: 17.0,
                  color: Colors.green,
                  fontWeight: FontWeight.w600,
                  decoration: TextDecoration.underline,
                ),
              ),
            )
          ],
        ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        key: _scaffoldKey,
        resizeToAvoidBottomPadding: false,
        resizeToAvoidBottomInset: true,
        body: SingleChildScrollView(
            child: Form(
                key: _formKey,
                child: Stack(children: <Widget>[
                  Container(
                      padding: EdgeInsets.symmetric(horizontal: 20.0),
                      child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            SizedBox(
                              height: 60.0,
                            ),
                            Padding(
                                padding: EdgeInsets.all(10.0),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    _showHello(),
                                    new Row(children: <Widget>[
                                      _showThere(),
                                      _showDot(),
                                    ]),
                                    _showEmailInput(),
                                    _showPasswordInput(),
                                    _showForgotPassword(),
                                    _showLogin(),
                                    _showGoogle(),
                                    _showNewRegister()
                                  ],
                                ))
                          ])),
                  //_showOTPAction(),
                ]))));
  }
}


执行登录的上述代码部分:

    void _login() {
            final form = _formKey.currentState;
        
            if (form.validate()) {
              form.save();
              _registerUser();
            }
          }
        
          void _registerUser() async {
            setState(() => _isSubmitting = true);
            http.Response response = await http.post(
                'http://192.168.43.9:1337/auth/local',
                body: {"identifier": _email, "password": _password});
            final responseData = json.decode(response.body);
            if (response.statusCode == 200) {
              setState(() => _isSubmitting = false);
              _showSuccessSnack();
              _redirectUser();
              print(responseData);
            } else {
              setState(() => _isSubmitting = false);
              final String errorMsg = responseData['message'];
              _showErrorSnack(errorMsg);
            }
          }
        
          void _showSuccessSnack() {
            final snackbar = SnackBar(
                content: Text(' User successfully logged in ',
                    style:
                        GoogleFonts.montserrat(color: Colors.green, fontSize: 16.0)));
            _scaffoldKey.currentState.showSnackBar(snackbar);
            _formKey.currentState.reset();
          }
        
          void _showErrorSnack(String errorMsg) {
            final snackbar = SnackBar(
                content: Text(errorMsg,
                    style: GoogleFonts.montserrat(color: Colors.red, fontSize: 16.0)));
            _scaffoldKey.currentState.showSnackBar(snackbar);
            throw Exception('Error logging in: $errorMsg');
          }
        
          void _redirectUser() {
            Future.delayed(Duration(seconds: 2), () {
              Navigator.pushReplacementNamed(context, '/intro');
            });
          }

错误

E/flutter ( 4862): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'String'
E/flutter ( 4862): #0      WelcomeBackPageState._registerUser (package:oristore/screens/auth/welcome_back_page.dart:182:20)
E/flutter ( 4862): <asynchronous suspension>
E/flutter ( 4862): #1      WelcomeBackPageState._login (package:oristore/screens/auth/welcome_back_page.dart:165:7)
E/flutter ( 4862): #2      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:992:19)
E/flutter ( 4862): #3      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:1098:38)
E/flutter ( 4862): #4      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:184:24)
E/flutter ( 4862): #5      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:524:11)
E/flutter ( 4862): #6      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:284:5)
E/flutter ( 4862): #7      BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:219:7)
E/flutter ( 4862): #8      PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:477:9)
E/flutter ( 4862): #9      PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:78:12)
E/flutter ( 4862): #10     PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:124:9)
E/flutter ( 4862): #11     _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:377:8)
E/flutter ( 4862): #12     PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:122:18)
E/flutter ( 4862): #13     PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:108:7)
E/flutter ( 4862): #14     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:220:19)
E/flutter ( 4862): #15     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:200:22)
E/flutter ( 4862): #16     GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:158:7)
E/flutter ( 4862): #17     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:104:7)
E/flutter ( 4862): #18     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:88:7)
E/flutter ( 4862): #19     _rootRunUnary (dart:async/zone.dart:1206:13)
E/flutter ( 4862): #20     _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter ( 4862): #21     _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
E/flutter ( 4862): #22     _invoke1 (dart:ui/hooks.dart:267:10)
E/flutter ( 4862): #23     _dispatchPointerDataPacket (dart:ui/hooks.dart:176:5)
E/flutter ( 4862):
   

共有2个答案

昝唯
2023-03-14

保存:(val)=

应添加到textformfield输入中,以便val不会返回null。

用整个flutter应用程序重新启动服务器api解决了这个问题。现在,用户可以成功登录。

别峻
2023-03-14

尝试使用此val?。长度使val为空。

 类似资料:
  • 我对使用颤振和特定于平台的代码非常陌生,所以如果这是一个愚蠢的问题,请原谅我。我正在使用一个事件通道将数据从android端返回到Flatter。我正在返回一份清单 但是,当我试图添加它时,它给出了一个异常,“未处理的异常:类型'列表'不是类型'列表'的子类型 这是我要将贴图对象添加到的列表。 列表 这是我的添加代码。忽略print语句。 我尝试过像cast或from这样的方法,但它对我不起作用,

  • 更新:感谢@Rjulcaa回答我的地图现在是一个列表,但是列表没有显示在用户界面上。我转过来,我需要用FutureBuilder来处理未来,所以如果有人面临这个问题,记得在你的用户界面主体中添加一个FutureBuilder,并在构建器上返回你想要显示的小部件。 我正在制作一个todo列表教程,我正在尝试添加JSON上的编码功能,我的todoList将其保存在SharedReferences上,当

  • 上面的代码给出了警告未处理的异常:类型'double'不是类型'string'的子类型

  • 我试图解析json,将其打印到控制台,然后放入ListView.builder并得到这个错误:键入'_InternalLinkedHashMap 我要怎么修? 列表数据 API服务 模型 非常感谢您的回答..................................................................................................

  • 我正在解码一个响应体,我得到了错误: 我在Udemy上学习颤振教程时,正在尝试使用API。教程说要使用https://javiercbk.github.io/json_to_dart/将JSON转换为Dart。我把JSON从https://www.openbrewerydb.org/并将其转换为Dart,但我遇到的问题是,当我尝试解码API时,我得到了未处理的错误异常:“List”类型不是“Map