当用户由于输入错误的登录数据(电子邮件或密码)而无法登录系统时,如何显示错误? 我希望此信息显示在电子邮件表单上方。
当我将错误的数据放入表单时,响应正文会在控制台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(),
],
)
)
]
)
)
),
);
}
感谢您的帮助:)
答案 0 :(得分:0)
您可以使用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!!");
}
}