如何在Flutter应用程序中保存登录名和用户信息

时间:2019-04-03 20:21:35

标签: flutter authorization basic-authentication flutter-dependencies

我想在登录后保存我的登录名,并将用户信息保存在模型中。

我该怎么办?我遵循了this文档,但不适用于我。

我想要同时在ios和android中

这是我目前的代码:

我的登录页面:

if not isCorrectType(data, ArgType):
    raise TypeError("data is not correct type")
else:
    myfun(data)

这是我的登录功能:

import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/services.dart';
import '../../common/apifunctions/requestLoginAPI.dart';
import 'package:gradient_widgets/gradient_widgets.dart';

class UserLoginPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _UserLoginPage();
  }
}

class _UserLoginPage extends State<UserLoginPage> {
  final TextEditingController _mobileController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _saveCurrentRoute('/UserLogin');
  }

  _saveCurrentRoute(String lastRoute) async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    await preferences.setString('LastScreenRoute', lastRoute);
  }

  void _gloginButton() {
    Navigator.pushReplacementNamed(context, '/Home');
  }

  void _registerButton() {
    Navigator.pushNamed(context, '/UserRegister');
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () {
          if (Navigator.canPop(context)) {
            Navigator.of(context).pushNamedAndRemoveUntil(
                '/Home', (Route<dynamic> route) => false);
          } else {
            Navigator.of(context).pushReplacementNamed('/Home');
          }
        },
        child: Scaffold(
          body: Column(
            children: <Widget>[
              Image.asset('assets/img/LRUI.png'),
              Form(
                child: Container(
                  //padding: EdgeInsets.only(top: 100.0),
                  margin: EdgeInsets.all(35.0),
                  child: Center(
                    child: Center(
                      child: SingleChildScrollView(
                        child: Column(
                          children: <Widget>[
                            SizedBox(
                              height: 99.0,
                            ),
                            TextFormField(
                              controller: _mobileController,
                              decoration: InputDecoration(
                                labelText: 'رقم الجوال',
                                hintText: "رقم الجوال يجب أن يكون عشر ارقام",
                              ),
                              style: TextStyle(
                                fontSize: 18.0,
                                color: Colors.grey,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            SizedBox(height: 11.0),
                            TextFormField(
                              controller: _passwordController,
                              decoration: InputDecoration(
                                labelText: 'الرقم السري',
                              ),
                              obscureText: true,
                              style: TextStyle(
                                fontSize: 18.0,
                                color: Colors.grey,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            SizedBox(
                              height: 40.0,
                            ),
                            GradientButton(
                              gradient: const LinearGradient(
                                begin: Alignment.topLeft,
                                end: Alignment.bottomCenter,
                                colors: const <Color>[
                                  Color(0xff4caf4e),
                                  Color(0xff71c071),
                                ],
                              ),
                              callback: () {
                                SystemChannels.textInput
                                    .invokeMethod('TextInput.hide');
                                requestLoginAPI(context, _mobileController.text,
                                    _passwordController.text);
                              },
                              textStyle: TextStyle(
                                  color: Colors.white, fontSize: 16.0),
                              shapeRadius: BorderRadius.circular(10.0),
                              child: Text(
                                "دخول",
                              ),
                              increaseHeightBy: 20.0,
                              increaseWidthBy: 140.0,
                            ),
                            SizedBox(
                              height: 35.0,
                            ),
                            FlatButton(
                              child: Text('دخول كضيف'),
                              onPressed: _gloginButton,
                            ),
                            FlatButton(
                              child: Text('تسجيل حساب جديد'),
                              onPressed: _registerButton,
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ));
  }
}

这是我保存登录信息的功能:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import '../functions/ saveCurrentLogin.dart';
import '../functions/showDialog.dart';
import 'dart:convert';
import '../../Models/Login.dart';
import '../../Models/User.dart';
import '../../Models/AuthResponse.dart';

Future<Login> requestLoginAPI(BuildContext context, String login, String password) async {
  final url = "http://188.166.172.146/Blooming/public/api/login";

  Map<String, String> body = {
    'login': login,
    'password': password,
  };

  final response = await http.post(
    url,
    body: body,
  );

  if (response.statusCode == 200) {
    final responseJson = json.decode(response.body);
    var token = new AuthResponse.fromJson(responseJson);

    saveCurrentLogin(responseJson);
    Navigator.of(context).pushReplacementNamed('/About');
    return Login.fromJson(responseJson);
  } else {
    final responseJson = json.decode(response.body);

    saveCurrentLogin(responseJson);
    showDialogSingleButton(context, "خطأ", "تأكد من معلومات الدخول", "موافق");

    return null;
  }
}

这些是我的模特:

授权响应模型

import 'package:shared_preferences/shared_preferences.dart';
import '../../Models/Login.dart';
import '../../Models/AuthResponse.dart';
import '../../Models/User.dart';

saveCurrentLogin(Map responseJson) async {
  SharedPreferences preferences = await SharedPreferences.getInstance();

var user;
  if ((responseJson != null && !responseJson.isEmpty)) {
    user = Login.fromJson(responseJson).login;
  } else {
    user = "";
  }
  var token = (responseJson != null && !responseJson.isEmpty) ? AuthResponse.fromJson(responseJson).token : "";
  var id = (responseJson != null && !responseJson.isEmpty) ? User.fromJson(responseJson).id : 0;
  var name = (responseJson != null && !responseJson.isEmpty) ? User.fromJson(responseJson).name : "";
  var email = (responseJson != null && !responseJson.isEmpty) ? User.fromJson(responseJson).email : "";
  var mobile = (responseJson != null && !responseJson.isEmpty) ? User.fromJson(responseJson).mobile : "";
  var active = (responseJson != null && !responseJson.isEmpty) ? User.fromJson(responseJson).active : 0;
  var confirmation_code = (responseJson != null && !responseJson.isEmpty) ? User.fromJson(responseJson).confirmation_code : "";
  var confirmed = (responseJson != null && !responseJson.isEmpty) ? User.fromJson(responseJson).confirmed : 0;

  await preferences.setString('token', (token != null && token.length > 0) ? token : "");

  await preferences.setInt('id', (id != null && id > 0) ? id : 0);
  await preferences.setString('name', (name != null && name.length > 0) ? name : ""); 
  await preferences.setString('email', (email != null && email.length > 0) ? email : ""); 
  await preferences.setString('mobile', (mobile != null && mobile.length > 0) ? mobile : ""); 
  await preferences.setInt('active', (active != null && active > 0) ? active : 0);
  await preferences.setString('confirmation_code', (confirmation_code != null && confirmation_code.length > 0) ? confirmation_code : ""); 
  await preferences.setInt('confirmed', (confirmed != null && confirmed > 0) ? confirmed : 0);

}

登录模型

import './User.dart';

class AuthResponse {
  final String token;
  User user;

  AuthResponse({
    this.token,
    this.user,
  });

factory AuthResponse.fromJson(Map<String, dynamic> parsedJson){
  return AuthResponse(
    token: parsedJson['token'],
    user: User.fromJson(parsedJson['user'])
  );
}


  Map<String, dynamic> toJson() => {
        'token': token,
        'user':user,
      };
}

用户模型

class Login {
  final String login;
  final String password;


  Login(this.login, this.password);

  Login.fromJson(Map<String, dynamic> json)
      : login = json['login'],
        password = json['password'];
}

1 个答案:

答案 0 :(得分:0)

您能否提供有关应用程序中哪个部分有问题以及收到哪些错误的更多详细信息?

关于存储登录名或用户信息的问题,您可以选择很多方法。身份验证成功后,您可以将数据存储在Firebase Cloud FirestoreRealtime Database之类的数据库中。这真的取决于您的用例。