首页 > 解决方案 > 当用户在 Flutter 中提供错误数据时如何显示错误

问题描述

当用户因输入错误的登录数据(电子邮件或密码)而无法登录系统时如何显示错误?我希望此信息出现在电子邮件表格上方。

当我在表单中抛出错误数据时,我的响应正文在控制台中返回我Wrong password or User does not exists,但我想在屏幕上显示此信息

我的登录api:

  makeLoginRequest(String email, password) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    Map data = {
      'email':emailController.text,
      'password':passwordController.text
    };
    var jsonResponse;
    var url = 'http://10.0.2.2:80/user/login';
    var response = await http.post(url, body:data);

    if(response.statusCode == 200){
      _isLoading = false;
      jsonResponse = json.decode(response.body);
      sharedPreferences.setInt("id", jsonResponse['id']);
      sharedPreferences.setString("firstName", jsonResponse['firstName']);
      sharedPreferences.setString("lastName", jsonResponse['lastName']);
      setState(() {
        Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (BuildContext context) => Home()), (Route<dynamic> route) => false);
      });

    }
    else{ 
      print(response.body);
    }
  }

我的用户界面:

@override
  Widget build(BuildContext context) {

    double height = MediaQuery.of(context).size.height;
    double width = MediaQuery.of(context).size.width;
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light
        .copyWith(statusBarColor: Colors.transparent));


    return Scaffold(
      body: SingleChildScrollView(
        child: Form(
          key: _formKey,
          child: Column(
            children: <Widget>[
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Padding(
                    padding: EdgeInsets.only(top: 20.0),
                    child: _headerSection(),
                  )
                ],
              ),
              Padding(
                padding: EdgeInsets.all(40.0),
                child: Column(
                  children: <Widget>[
                    SizedBox(height: 180.0),
                  _buildEmail(),
                  SizedBox(height: 30.0),
                  _buildPassword(),
                  SizedBox(height: 80.0),
                  _buttonSection(),
                  SizedBox(height: 40.0),
                  _helpText(),
                  ],
                )
              )
            ]
          )
        )
      ),
    );
  }

谢谢你的帮助 :)

标签: flutterdart

解决方案


您可以使用AlertDialog来显示错误消息,TextEditingController如果您愿意,可以使用 传递密码。我附上了一个可以运行的极简示例。正确的密码是“111”,否则会通过 ```AlertDialog```` 显示错误消息

编辑:更新代码以包含小吃吧

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final TextEditingController _controller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Builder(
        builder: (BuildContext context){
          return Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              TextField(
                controller: _controller,
              ),
              RaisedButton(
                onPressed: () => checkPassword(context, _controller.text),
                child: Text("Login",),
              ),
            ],
          );
        },
      )

    );
  }

  void checkPassword(BuildContext context, String password) {
    if (password != "111") {
      final snackBar = SnackBar(content: Text("$password is not correct!"));
      Scaffold.of(context).showSnackBar(snackBar);
      return;
    }
    print("Password corect!!");
  }
}

推荐阅读