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

由于

海嘉赐
2023-03-14

颤动新手试图做一个注册和登录屏幕^_^"

>

不会出现注册和登录中输入的无效/不完整详细信息的错误通知文本。这应该出现在注册/登录按钮之前。

当我尝试运行“打印登录”页面时,屏幕上什么也没有发生。

DART FILE OF SIGNUP BELOW:

    class SignUp extends StatefulWidget {
      const SignUp ({Key key}) : super(key: key);
      @override
      _SignUpState createState() => _SignUpState();
    }

    class _SignUpState extends State<SignUp> {
      String username;
      String useremail;
      String userpw;
      String errormessage = '';

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          backgroundColor: Colors.white,
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Image(
                  image: AssetImage('logo.png'),
                  width: 70.0,
                ),
                SizedBox(
                  height: 10.0,
                ),
                Container(
                  child: Text('Create Account'),
                ),
                SizedBox(
                  height: 15.0,
                ),
                Container(
                  width: 300.0,
                  child: TextField(
                      obscureText: false,
                      onChanged: (value) {
                        username = value;
                      }),
                ),
                SizedBox(
                  height: 8.0,
                ),
                Container(
                  width: 300.0,
                  child: TextField(
                      obscureText: false,
                      onChanged: (value) {
                        useremail = value;
                      }),
                ),
                SizedBox(
                  height: 8.0,
                ),
                Container(
                  width: 300.0,
                  child: TextField(
                      obscureText: true,
                      onChanged: (value) {
                        userpassword = value;
                      }),
                ),
                SizedBox(
                  height: 8.0,
                ),
                Container(
                  child: Text(
                    errormessage,
                    style: TextStyle(color: Colors.red[500]),
                  ),
                ),
                SizedBox(height: 12.0),
                Container(
                  margin: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
                  child: ElevatedButton(
                    onPressed: () {

                      Map json = {
                        "username": username,
                        "useremail": useremail,
                        "userpw": userpw,
                      };
                      //print(json);

                      UserSignUp(json).then((result) {
                        if (result['error'] != null) {
                          setState(() {
                            errormessage = result['error'];
                          });
                        } else {
                          setState(() {
                            errormessage = '';
                          });
                          Navigator.push(context,
                              MaterialPageRoute(builder: (context) => SignInPage()));
                        }
                      });
                    },
                    style: ElevatedButton.styleFrom(
                      primary: Color(0xff04A148C),
                      onPrimary: Colors.blue[900],
                      padding: EdgeInsets.only(
                          left: 70.0, top: 10.0, right: 70.0, bottom: 10.0),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10.0),
                      ),
                    ),
                    child: Text(
                      'Sign Up',
                      style: TextStyle(
                        color: Colors.white,
                        fontFamily: 'Roboto',
                        fontSize: 15.0,
                        fontWeight: FontWeight.w600,
                        letterSpacing: 1.0,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      }
    }




    DART FILE OF CONTROLLER BELOW:

    final appkey ="appkey random numbers";

    Future<Map> UserSignUp(Map json) async {
      json['appkey'] = appkey;
      final response = await http.post(
        Uri.parse('Sign Up URL'),
        headers: <String, String>{
          'Content-Type': 'application/json; charset=UTF-8',
        },
        body: jsonEncode(json),
      );

      print(response.body);
      if (response.statusCode == 200) {
        return jsonDecode(response.body);
      } else if (response.statusCode == 401) {
        Map error = jsonDecode(response.body);
        Map json = {
          "error": error['data'][0]['msg'],
        };

        return json;
      } else {
        throw Exception('Fail');
      }
    }

    Future<Map> UserSignIn(Map json) async {
      json['appkey'] = appkey;
      final response = await http.post(
        Uri.parse('Sign Up URL'),
        headers: <String, String>{
          'Content-Type': 'application/json;charset=UTF-8',
        },
        body: jsonEncode(json),
      );


      if (response.statusCode == 200) {
        return jsonDecode(response.body);
      } else if (response.statusCode == 400) {
        return jsonDecode(response.body);
      } else {
        throw Exception('Fail');
      }
    }
    


CODE IN THE RUN WINDOW WHEN SIGN-UP IS CLICKED WITH EMPTY TEXT FIELDS ARE BELOW:
    
Performing hot restart...
Syncing files to device AOSP on IA Emulator...
Restarted application in 679ms.
I/flutter (29028): null
I/chatty  (29028): uid=10085(com.example.appname) 1.ui identical 1 line
I/flutter (29028): null
I/flutter (29028): {username: null, useremail: null, userpassword: null}
E/flutter (29028): [ERROR:flutter/lib/ui/ui_dart_state.cc(213)] Unhandled Exception: type 'String' is not a subtype of type 'FutureOr<Map<dynamic, dynamic>>'
E/flutter (29028): #0      registerUser (package:appname/controller.dart:22:5)
E/flutter (29028): <asynchronous suspension>
E/flutter (29028):
p and Sign-in screens not showing:
Made a sign-up and login page with error notification text set to appear if there is incomplete or invalid details.
DART FILE OF SIGNUP BELOW:

class SignUp extends StatefulWidget {
  const SignUp ({Key key}) : super(key: key);
  @override
  _SignUpState createState() => _SignUpState();
}

class _SignUpState extends State<SignUp> {
  String username;
  String useremail;
  String userpw;
  String errormessage = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Image(
              image: AssetImage('logo.png'),
              width: 70.0,
            ),
            SizedBox(
              height: 10.0,
            ),
            Container(
              child: Text('Create Account'),
            ),
            SizedBox(
              height: 15.0,
            ),
            Container(
              width: 300.0,
              child: TextField(
                  obscureText: false,
                  onChanged: (value) {
                    username = value;
                  }),
            ),
            SizedBox(
              height: 8.0,
            ),
            Container(
              width: 300.0,
              child: TextField(
                  obscureText: false,
                  onChanged: (value) {
                    useremail = value;
                  }),
            ),
            SizedBox(
              height: 8.0,
            ),
            Container(
              width: 300.0,
              child: TextField(
                  obscureText: true,
                  onChanged: (value) {
                    userpassword = value;
                  }),
            ),
            SizedBox(
              height: 8.0,
            ),
            Container(
              child: Text(
                errormessage,
                style: TextStyle(color: Colors.red[500]),
              ),
            ),
            SizedBox(height: 12.0),
            Container(
              margin: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
              child: ElevatedButton(
                onPressed: () {

                  Map json = {
                    "username": username,
                    "useremail": useremail,
                    "userpw": userpw,
                  };
                  //print(json);

                  UserSignUp(json).then((result) {
                    if (result['error'] != null) {
                      setState(() {
                        errormessage = result['error'];
                      });
                    } else {
                      setState(() {
                        errormessage = '';
                      });
                      Navigator.push(context,
                          MaterialPageRoute(builder: (context) => SignInPage()));
                    }
                  });
                },
                style: ElevatedButton.styleFrom(
                  primary: Color(0xff04A148C),
                  onPrimary: Colors.blue[900],
                  padding: EdgeInsets.only(
                      left: 70.0, top: 10.0, right: 70.0, bottom: 10.0),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                ),
                child: Text(
                  'Sign Up',
                  style: TextStyle(
                    color: Colors.white,
                    fontFamily: 'Roboto',
                    fontSize: 15.0,
                    fontWeight: FontWeight.w600,
                    letterSpacing: 1.0,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}




DART FILE OF CONTROLLER BELOW:

final appkey ="appkey random numbers";

Future<Map> UserSignUp(Map json) async {
  json['appkey'] = appkey;
  final response = await http.post(
    Uri.parse('Sign Up URL'),
    headers: <String, String>{
      'Content Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(json),
  );

  print(response.body);
  if (response.statusCode == 200) {
    return jsonDecode(response.body);
  } else if (response.statusCode == 401) {
    Map error = jsonDecode(response.body);
    Map json = {
      "error": error['data'][0]['msg'],
    };

    return json;
  } else {
    throw Exception('Fail');
  }
}

Future<Map> UserSignIn(Map json) async {
  json['appkey'] = appkey;
  final response = await http.post(
    Uri.parse('Sign Up URL'),
    headers: <String, String>{
      'Content Type': 'application/json;charset=UTF-8',
    },
    body: jsonEncode(json),
  );


  if (response.statusCode == 200) {
    return jsonDecode(response.body);
  } else if (response.statusCode == 400) {
    return jsonDecode(response.body);
  } else {
    throw Exception('Fail');
  }
}

共有2个答案

黄俊誉
2023-03-14

我明白了,你需要使用waitjsonDecode函数,因为它是一个未来。Ex:

Map res = await jsonDecode(response.body);
return res;

替换:

final appkey ="appkey random numbers";

Future<Map> UserSignUp(Map json) async {
  json['appkey'] = appkey;
  final response = await http.post(
    Uri.parse('Sign Up URL'),
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(json),
  );

  print(response.body);
  if (response.statusCode == 200) {
    return jsonDecode(response.body);
  } else if (response.statusCode == 401) {
    Map error = jsonDecode(response.body);
    Map json = {
      "error": error['data'][0]['msg'],
    };

    return json;
  } else {
    throw Exception('Fail');
  }
}

Future<Map> UserSignIn(Map json) async {
  json['appkey'] = appkey;
  final response = await http.post(
    Uri.parse('Sign Up URL'),
    headers: <String, String>{
      'Content-Type': 'application/json;charset=UTF-8',
    },
    body: jsonEncode(json),
  );


  if (response.statusCode == 200) {
    return jsonDecode(response.body);
  } else if (response.statusCode == 400) {
    return jsonDecode(response.body);
  } else {
    throw Exception('Fail');
  }
}

与:

final appkey ="appkey random numbers";

Future<Map> UserSignUp(Map json) async {
  json['appkey'] = appkey;
  final response = await http.post(
    Uri.parse('Sign Up URL'),
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(json),
  );

  print(response.body);
  if (response.statusCode == 200) {
    Map data = await jsonDecode(response.body);
    return data;
  } else if (response.statusCode == 401) {
    Map error = await jsonDecode(response.body);
    Map json = {
      "error": error['data'][0]['msg'],
    };

    return json;
  } else {
    throw Exception('Fail');
  }
}

Future<Map> UserSignIn(Map json) async {
  json['appkey'] = appkey;
  final response = await http.post(
    Uri.parse('Sign Up URL'),
    headers: <String, String>{
      'Content-Type': 'application/json;charset=UTF-8',
    },
    body: jsonEncode(json),
  );


  if (response.statusCode == 200) {
    Map data = await jsonDecode(response.body);
    return data;
  } else if (response.statusCode == 400) {
    Map data = await jsonDecode(response.body);
    return data;
  } else {
    throw Exception('Fail');
  }
}
堵德曜
2023-03-14

Content-Type有连字符。在标题中添加一个。

 类似资料:
  • 我有一个小难题来解决这个问题。 我有一个用户和一个管理员角色。 用户应该能够列出除管理员以外的所有用户。管理员可以列出所有用户。 我想到的第一个解决方案是检查控制器级别的角色: 但是我更想做的是在路线层面上,保持控制器更干净,但不知何故它确实起作用了。它只列出用户,即使我作为管理员登录。 有什么建议吗?谢谢!

  • 例如,我们可能希望一些路线只有在用户登录或接受条款和条件后才可访问。 我们可以使用路由哨兵来检查这些条件并控制对路由的访问。 路由哨兵还可以控制用户是否可以离开某个路由。 例如,假设用户已将信息键入页面上的表单,但尚未提交表单。 如果这时离开页面,他们将丢失信息。 如果用户尝试离开路由而不是提交或保存信息,我们可以提示用户。 Angular 提供了五种路由拦截哨兵: CanActive 激活拦截

  • 每个路由可以有不同的属性; 一些常见的属性是: path - 应用程序在特定路由上时在浏览器中显示的URL component - 当应用程序在特定路由上时要呈现的组件 pathMatch - 默认为’prefix’的可选属性。 确定是匹配完整的网址还是仅匹配开头。 当定义一个具有空路径字符串的路径设置pathMatch为’full’时,否则它将匹配所有路径。 children - 表示此路由的子

  • 通过Group可以实现路由分组,Group 路由分组可以简化你的路由撰写: 有两种方法来使用Group: 第一种,创建Group对象,通过Group方法传入 g := tango.NewGroup() g.Get("/1", func() string { return "/1" }) g.Post("/2", func() string { return "/2" }) o :=

  • Tango支持4种形式的路由匹配规则 静态路由 tg.Get("/", new(Action)) tg.Get("/static", new(Action))匹配 URL:/ 到 Action结构体的Get函数 匹配 URL:/static 到 Action结构体的Get函数 命名路由 tg.Get("/:name", new(Action)) tg.Get("/(:name)", new(Act

  • 英文原文: http://emberjs.com/guides/routing/asynchronous-routing/ 本节内容主要介绍一些路由的高级特性,以及路由是如何处理应用中的一些复杂异步逻辑的。 承诺简介 Ember在路由中处理异步逻辑的方案主要依赖于承诺(Promise)。简单地说,承诺就是代表了最后的值的对象。承诺可以被履行(成功的获得了最后的结果)也可以被拒绝(没有获得最后的结果