在flutter中通过rest api登录验证用户

Posted

技术标签:

【中文标题】在flutter中通过rest api登录验证用户【英文标题】:Login Validate User through rest api in flutter 【发布时间】:2020-05-13 02:59:54 【问题描述】:

我使用 Rest API 进行了登录。我的应用程序的工作方式就像用户名和密码正确,然后转到应用程序的主页。如果为假,则在页面上引发异常。问题是凭据是真还是假。它在下一个上下文或屏幕上显示循环进度指示器。如果凭据为真。它显示像 enter image description here 然后 enter image description here 然后 MainApp enter image description here

如果 Crendential 为 false,则异常页面显示在 MainAppScreen 的 else 中。 但是如果用户凭据错误,我想在这样的表单下显示错误。enter image description here 由于没有得到所需的输出,我进行了两天的验证。我的代码文件 ma​​in.dart

import 'package:flutter/material.dart';
import 'package:testing/api.dart';
import 'package:testing/sucess.dart';

main() 
  runApp(MyApp());


class MyApp extends StatelessWidget 
  @override
  Widget build(BuildContext context) 
    return MaterialApp(
      home: SignIn(),
    );
  


class SignIn extends StatefulWidget 
  @override
  _SignInState createState() => _SignInState();


class _SignInState extends State<SignIn> 
  TextStyle style = TextStyle(fontFamily: 'Montserrat', fontSize: 20.0);
  //Gettting the JwtToken object and making the instance of it

  Future<LoginResponse> _futureJwt;
  final TextEditingController _controller = TextEditingController();
  //Getting the password from the textField
  final TextEditingController _controller1 = TextEditingController();


  @override
  Widget build(BuildContext context) 
    return Scaffold(
      // appBar: AppBar(

      // ),
      backgroundColor: Colors.white,
      body: Container(
        alignment: Alignment.center,
        // padding: const EdgeInsets.all(8.0),
        //if Field have the null values then Get the value from the textField

        child: (_futureJwt == null)
            ? SingleChildScrollView(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    // SizedBox(
                    //   height: MediaQuery.of(context).size.height * 1 / 3,
                    //   child: Image.asset(
                    //     "assets/IMG_2382.png",
                    //     fit: BoxFit.cover,
                    //   ),
                    // ),
                    // SizedBox(height: 45.0),
                    Padding(
                      padding: const EdgeInsets.only(left: 30,right: 30),
                      child: TextField(
                        style: style,
                        decoration: InputDecoration(

                          contentPadding:
                              EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
                          hintText: "Email",
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(20.0),
                          ),
                        ),
                        controller: _controller,
                      ),
                    ),
                    SizedBox(height: 25.0),
                    Padding(
                      padding: const EdgeInsets.only(left: 30,right: 30),
                      child: TextField(
                        controller: _controller1,
                        obscureText: true,
                        style: style,
                        decoration: InputDecoration(
                          contentPadding:
                              EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
                          hintText: "Password",
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(20.0),
                          ),
                        ),
                      ),
                    ),
                    SizedBox(
                      height: 35.0,
                    ),
                    Material(
                      elevation: 5.0,
                      borderRadius: BorderRadius.circular(5.0),
                      color: Colors.white,
                      child: Container(
                        width: 150,
                        height: 50,
                        child: RaisedButton(                    
                          child: Text(
                            "Login",
                            textAlign: TextAlign.center,
                            style: style.copyWith(
                                color: Colors.white,
                                fontWeight: FontWeight.bold),

                          ),
                          color: Colors.grey[800],
                          // padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
                          onPressed: () 
                            setState(() 
                              _futureJwt = createLoginState(
                                  _controller.text, _controller1.text);
                            );
                          ,
                        ),
                      ),
                    ),
                    SizedBox(
                      height: 15.0,
                    ),
                  ],
                ),
              )
            //If the Conditiion (_futureJwt == null) is false then
            : FutureBuilder<LoginResponse>(
                //refer the object to the future
                future: _futureJwt,
                //
                builder: (context, snapshot) 
                  //if the data is getting
                  if (snapshot.hasData) 
                    var token = snapshot.data.token;
                    print(token);
                    return Sucess();
                  
                  //if the data results an error
                  else if (snapshot.hasError) 
                    return Text("$snapshot.error");
                  

                  return CircularProgressIndicator();
                ,
              ),
      ),
    );
  


sucess.dart

import 'package:flutter/material.dart';

class Sucess extends StatelessWidget 
  @override
  Widget build(BuildContext context) 
    return Container(
      child: Text('data'),
    );
  


api.dart

import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:async';

Future<LoginResponse> createLoginState(String username, String password) async 
  final http.Response response = await http.post(
      'http://192.168.43.76//soledesign/wp-json/jwt-auth/v1/token',
      headers: <String, String>
        'Accept': 'application/json',
      ,
      body: 
        'username': username,
        'password': password,
      );

  if (response.statusCode == 200) 
    print(response.body);
    return LoginResponse.fromJson(json.decode(response.body));
   else 
    throw Exception('Failed to create album.');
  


class LoginResponse 
  String token;
  String userEmail;
  String userNicename;
  String userDisplayName;

  LoginResponse(
      this.token, this.userEmail, this.userNicename, this.userDisplayName);

  LoginResponse.fromJson(Map<String, dynamic> json) 
    token = json['token'];
    userEmail = json['user_email'];
    userNicename = json['user_nicename'];
    userDisplayName = json['user_display_name'];
  


【问题讨论】:

【参考方案1】:

您需要做的是添加一个警告框,当 json 响应有错误消息时显示该框。像这样: if (json['ErrorMessage] != null) ShowAlertDialog();

【讨论】:

以上是关于在flutter中通过rest api登录验证用户的主要内容,如果未能解决你的问题,请参考以下文章

在Salesforce中通过REST API编辑自定义对象

保护未经身份验证的 REST API

如何在 Flutter 集成测试中最好地存根/模拟 rest API 调用

在android中通过firebase进行Facebook登录时身份验证失败

来自 Flutter App 的 Firebase Id Token 未在 REST 服务器上验证

在本机反应中通过 rest api 通知