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

问题描述 投票:0回答:1

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

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

我想同时在ios和android中使用它

这是我的当前代码:

我的登录页面:

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);

}

这些是我的模特:

Auth响应模型

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'];
}

用户模型

class User {
  final int id;
  final String name;
  final String email;
  final String mobile;
  final int active;
  final String confirmation_code;
  final int confirmed;

  User({
    this.id,
    this.name,
    this.email,
    this.mobile,
    this.active,
    this.confirmation_code,
    this.confirmed,
  });

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      id: json['id'],
      name: json['name'],
      email: json['email'],
      mobile: json['mobile'],
      active: json['active'],
      confirmation_code: json['confirmation_code'],
      confirmed: json['confirmed'],
    );
  }

  Map<String, dynamic> toJson() => {
        'id': id,
        'name': name,
        'email':email,
        'mobile':mobile,
        'active':active,
        'confirmation_code':confirmation_code,
        'confirmed':confirmed,
      };
}
flutter authorization basic-authentication flutter-dependencies
1个回答
0
投票

您可以使用flutter_secure_storage ...

© www.soinside.com 2019 - 2024. All rights reserved.