How to store device info in shared preference in flutter - flutter

in this question i want to store device info into shared preferences becuase i want to access device info anywhere from application. Hope you understand the question. your small help can made my day :)
Here is some code i've tried
Future deviceinfo() async {
if (Platform.isAndroid) {
AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
print("Hey Android User");
print('Running on ${androidInfo.id}');
print('Running on ${androidInfo.isPhysicalDevice}');
print('Running on ${androidInfo.fingerprint}');
//Here in this line error
SharedPreferences devicepref = await SharedPreferences.getInstance();
devicepref.setString('deviceinfo', androidInfo);
} else if (Platform.isIOS) {
IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
print("Hey IOS User");
print('Running on ${iosInfo.utsname.machine}');
}
}

To Save your info in memory, set sharedprefs using :
SharedPreferences prefs = await SharedPreferences.getInstance();
if (Platform.isAndroid) {
AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
prefs.setString('deviceinfo', androidInfo.id});
prefs.setString('deviceID', your_android_id_value});
prefs.setString('deviceName', your_android_name_value});
} else if (Platform.isIOS) {
IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
prefs.setString('deviceinfo', iosInfo.utsname.machine});
prefs.setString('deviceID', your_ios_id_value});
prefs.setString('deviceName', your_ios_name_value});
}
To get info from memory using shared prefs :
SharedPreferences prefs = await SharedPreferences.getInstance();
String info=prefs.getString("deviceinfo");
String info=prefs.getString("deviceID");
String info=prefs.getString("deviceName");
print("info : ${info}");
print("ID: ${deviceID}");
print("Name: ${deviceName}");
This will help you.

Related

How to get android device version - Flutter

I have been trying to get the Android device version (For example 11, 12). I have been trying to get only the number
This is what I have done till now
void checkVersion(){
print(Platform.operatingSystemVersion); // it prints "sdk_gphone64_arm64-userdebug 12 S2B2.211203.006 8015633 dev-keys"
// I'm able to fetch the version number by splitting the string
// but the problem is that format of above string will vary by
// operating system, so not suitable for parsing
int platformVersion = int.parse(Platform.operatingSystemVersion.split(' ')[1]); it prints '12'
}
Use the device_info_plus plugin and get Android, iOS, macOS, Linux versions with the following snippet:
Future<String> _getOsVersion() async {
final deviceInfo = DeviceInfoPlugin();
if (Platform.isAndroid) {
final info = await deviceInfo.androidInfo;
return info.version.release ?? 'Unknown';
}
if (Platform.isIOS) {
final info = await deviceInfo.iosInfo;
return info.systemVersion ?? 'Unknown';
}
if (Platform.isMacOS) {
final info = await deviceInfo.macOsInfo;
return info.osRelease;
}
if (Platform.isLinux) {
final info = await deviceInfo.linuxInfo;
return info.version ?? 'Unknown';
}
return 'Unknown Version';
}
Try device_info_plus to get any device information you need.
Future<String?> getAndroidVersion() async {
if (Platform.isAndroid) {
DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
return androidInfo.version.release;
}
throw UnsupportedError("Platform is not Android");
}
You can use device_info_plus package to get the device version:
DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
final androidInfo = await deviceInfoPlugin.androidInfo;
return androidInfo.version.sdkInt;
Or if you don't want to use any external plugin, you can use Platform.operatingSystemVersion. But it'll give you:
"sdk_gphone64_arm64-userdebug 12 S2B2.211203.006 8015633 dev-keys"
So what you did is right. You've to split the string and get the device version:
final systemVerion = Platform.operatingSystemVersion;
int deviceVersion = int.parse(operatingSystemVersion.split(' ')[1]);
print(deviceVersion);
//prints '12'

An optimize way for tryAutoLogin function in flutter?

I want to create a function for auto login like Facebook in flutter but don't know the best way to do it.
My function for login and auto login, I used SharedPreferences plugin for store data.
SignIn function:
Future<void> signIn(String userName, String pass) async {
final url = Uri.parse('MyAPI_login');// sorry it for privacy
debugPrint("$userName / $pass");
try {
var respone = await http.post(url, body: {
'user_name': userName,
'password': pass,
'platform': 'mobile',
'device_token': '',
});
final reponseData = jsonDecode(respone.body);
_userName = userName;
_token = reponseData['data']['accessToken'];
_expiryDate = DateTime.now().add(Duration(
seconds: int.parse(reponseData['data']['tokenExpireAt'].toString())));
_refreshToken = reponseData['data']['refreshToken'].toString();
_timerRefreshToken =
int.parse(reponseData['data']['refreshTokenExpireAt'].toString());
// debugPrint(
// '$_token \n $_expiryDate \n $_refreshToken \n $_timerRefreshToken');
notifyListeners();
final prefs = await SharedPreferences.getInstance();
final userData = json.encode({
'_userId': _userName.toString(),
'token': _token.toString(),
'expiryDate': _expiryDate!.toIso8601String(),
'refreshToken': _refreshToken,
'timerRefreshToken': _timerRefreshToken.toString(),
});
await prefs.setString('userData', userData);
} catch (error) {
throw Exception(error.toString());
}}
TryAutoLogin function:
Future<bool> tryAutoLogin() async {
final prefs = await SharedPreferences.getInstance();
if (!prefs.containsKey('userData')) {
return false;
}
final extractedUserData = json
.decode(prefs.getString('userData').toString()) as Map<String, dynamic>;
final expiryDate =
DateTime.parse(extractedUserData['expiryDate'].toString());
if (expiryDate.isBefore(DateTime.now())) {
_token = extractedUserData['refreshToken'].toString();
_expiryDate = DateTime.now().add(
Duration(seconds: int.parse(extractedUserData['timerRefreshToken'])));
_refreshNewToken(extractedUserData['refreshToken'].toString());
}
return true;}
RefreshNewToken function:
Future<void> _refreshNewToken(String oldRefreshToken) async {
final url =
Uri.parse('MyAPI_refreshtoken');
var respone = await http.post(url, body: {'refreshToken': oldRefreshToken});
debugPrint(respone.body);}
My API for login response is like this:
{"data":{"tokenKey":"Authorization","tokenType":"Bearer","accessToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl9pZCI6ImE1YzkyMTQwLTA3Y2YtMTFlZC1hNDQ2LTYzY2YyNjNiZjllMiIsInVzZXJfaWQiOiJDODAzQ0I3RS1CQTcyLTQ4NjgtQjdEMC05NkRBOUNCREQyMTkiLCJ1c2VyX25hbWUiOiIxMDAyMCIsImZ1bGxfbmFtZSI6IkzDqiBUaOG7iyBMacOqbiIsImlzQWRtaW5pc3RyYXRvciI6MCwidXNlcl9jb21wYW5pZXMiOltdLCJpYXQiOjE2NTgyODIzOTMsImV4cCI6MTY1ODI4NTk5M30.3kMByfweUhzQM-4d5S0G7tUaC0e-nZLJF3_dbdV_7fM","tokenExpireAt":1658285940964,"refreshToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl9pZCI6ImE1YzkyMTQwLTA3Y2YtMTFlZC1hNDQ2LTYzY2YyNjNiZjllMiIsInVzZXJfaWQiOiJDODAzQ0I3RS1CQTcyLTQ4NjgtQjdEMC05NkRBOUNCREQyMTkiLCJ1c2VyX25hbWUiOiIxMDAyMCIsImZ1bGxfbmFtZSI6IkzDqiBUaOG7iyBMacOqbiIsImlzQWRtaW5pc3RyYXRvciI6MCwidXNlcl9jb21wYW5pZXMiOltdLCJpYXQiOjE2NTgyODIzOTMsImV4cCI6MTY1ODM2ODc5M30.Bv7PZrnx9zDzwIuxNMppFxlwZlJEnthVjEYBKYl-aWM","refreshTokenExpireAt":1658368740964},"message":"Logged in successfully!","status":200,"errors":null}
Also, my API has a refresh token request, it returns like this:
{"data":{"tokenKey":"Authorization","tokenType":"Bearer","accessToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl9pZCI6ImE1ZjQyOGUwLTA3Y2YtMTFlZC1hNDQ2LTYzY2YyNjNiZjllMiIsInVzZXJfaWQiOiJDODAzQ0I3RS1CQTcyLTQ4NjgtQjdEMC05NkRBOUNCREQyMTkiLCJ1c2VyX25hbWUiOiIxMDAyMCIsImZ1bGxfbmFtZSI6IkzDqiBUaOG7iyBMacOqbiIsImlzQWRtaW5pc3RyYXRvciI6MCwidXNlcl9jb21wYW5pZXMiOltdLCJpYXQiOjE2NTgyODIzOTQsImV4cCI6MTY1ODI4NTk5NH0.wcyouoprMHFnRD4_oSpP9RSasxMBrktX6nZI2x2PQec","tokenExpireAt":1658285940242,"refreshToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl9pZCI6ImE1ZjQyOGUwLTA3Y2YtMTFlZC1hNDQ2LTYzY2YyNjNiZjllMiIsInVzZXJfaWQiOiJDODAzQ0I3RS1CQTcyLTQ4NjgtQjdEMC05NkRBOUNCREQyMTkiLCJ1c2VyX25hbWUiOiIxMDAyMCIsImZ1bGxfbmFtZSI6IkzDqiBUaOG7iyBMacOqbiIsImlzQWRtaW5pc3RyYXRvciI6MCwidXNlcl9jb21wYW5pZXMiOltdLCJpYXQiOjE2NTgyODIzOTQsImV4cCI6MTY1ODM2ODc5NH0.y-8MP4M_1LzCwmqo_KQZGyQXkycrxdOLWz_fdqIPRyQ","refreshTokenExpireAt":1658368740242},"message":"Request successfully!","status":200,"errors":null}

how to initialize sharedPreferences flutter?

In order to Authenticate to Api, I created AuthProvider class to authenticate, after getting accessToken from the Api,I stored the token using sharedPreferences,I wanted to check if the user loggedIn or not, so I initialized sharedPreferences to return a boolean value if it contains the token... as shown in the code bellow:
class AuthProvider with ChangeNotifier{
bool _isLoading = false;
bool get isLoading => _isLoading;
User user = User();
late SharedPreferences prefs ;
String token = '';
Map<String, String> _mainHeaders = {
'Content-Type': 'application/json; charset=UTF-8',
};
void updateHeader(String token) {
_mainHeaders = {
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'Bearer $token',
};
}
Future<ResponseModel> login(String username, String password) async {
print("Getting token");
//print(authRepo.getUserToken().toString());
_isLoading = true;
notifyListeners();
http.Response response = await dologin(username, password);
// print('${response.body.}');
var answer = User.fromJson(jsonDecode(response.body));
print('the result is : ${answer.token}');
print('level 1: ${response.body.toString()}');
late ResponseModel responseModel;
print(response.statusCode);
if (response.statusCode == 200) {
//authRepo.saveUserToken((response.body["token"]).toString());
print("Backend token: ${response.body.toString()}");
responseModel = ResponseModel(true, answer.token!);
// SharedPreferences prefs = await SharedPreferences.getInstance();
// prefs.setString(ApiConstants.kEY_ACCESS_TOKEN, answer.token!);
storeToken(answer.token!);
} else {
responseModel = ResponseModel(false, response.reasonPhrase!);
}
_isLoading = false;
notifyListeners();
return responseModel;
}
bool userLoggedIn() =>
prefs.containsKey(ApiConstants.kEY_ACCESS_TOKEN) ? true : false;
// bool clearSharedData() => authRepo.clearSharedData();
void storeToken(String token) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString(ApiConstants.kEY_ACCESS_TOKEN, token);
print('the token is here : ${token}');
}
...
in main.dart I created a consumer to check if the user is loggedIn or not :
child: MaterialApp(
home: Consumer<AuthProvider>(
builder: ((context, auth, _){
return auth.userLoggedIn() ? const HomePage() : const loginScreen();
})
),
...
when I hit run I got the following error in my console:
The following LateError was thrown building Consumer(dirty, dependencies: [_InheritedProviderScope<AuthProvider?>]):
LateInitializationError: Field 'prefs' has not been initialized.
The relevant error-causing widget was
Consumer.
PS : I tried to initialize sharedPreferences : SharedPreferences? prefs;
the error would be:
Null check operator used on a null value.
...
You're getting the error because you've marked your prefs as late but you haven't initialised it (as written in the error message). Just get rid of the line late SharedPreferences prefs; at the top and ensure that you initialise it each time you need it within the method. I.e. call await SharedPreferences.getInstance(); each time.
Future<bool> userLoggedIn() async{
prefs = await SharedPreferences.getInstance();
prefs.containsKey(ApiConstants.kEY_ACCESS_TOKEN) ? true : false;
}
Change userLoggedIn getter to this.
You can call a function from init state and check the sharedprefrences in it like
late SharedPreferences prefs;
//initialize shared prefrences then access it
void initState() {
super.initState();
sharedData();
}
void sharedData() async {
prefs = await SharedPreferences.getInstance();
}
void storeToken(String token) async {
prefs = await SharedPreferences.getInstance();
prefs.setString(ApiConstants.kEY_ACCESS_TOKEN, token);
print('the token is here : ${token}');
}

Shared Preferences misplugin

i do same exactly as youtube says but in the end i got this error, do you know what is the problem ?
im using flutter 2.8.1 shared_preferences: ^2.0.13
this is the code
class _AppHomeState extends State<AppHome> {
final Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
Future loadData() async {
final SharedPreferences prefs = await _prefs;
var stringSet = await prefs.getString('sets');
List setList = jsonDecode(stringSet!);
for (var sets in setList) {
c.setList.add(SetModel().fromJson(sets));
}
}
Future saveData() async {
final SharedPreferences prefs = await _prefs;
List items = c.setList.map((e) => e.toJson()).toList();
prefs.setString('sets', jsonEncode(items));
}
try running
flutter clean
see issue here
Modify line number 31 as below:
final SharedPreferences _prefs = SharedPreferences.getInstance();
This will fix your problem.

How can I make this work? My shared preferences seem to store the wrong value?

I have these functions to set, remove etc variables I want globally available. I fear it might be just a small mistake on my behalf. What can I do to fix this?
static setUserId(userId, value) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setInt('userId', value);
}
static getUserId() async {
final prefs = await SharedPreferences.getInstance();
prefs.getInt('userId') ?? 0;
}
static removeUserId() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove('userId');
}
static removeAllPreferences() async {
final prefs = await SharedPreferences.getInstance();
await prefs.clear();
}
}
var userId = user.id;
var value = userId?.toInt();
AccountPreferences.setUserId('userId', value);
var companyId = user.role![0].companyId;
var test = AccountPreferences.getUserId();
print(test); ```
When I run the code above all I print out is an instance of Future<dynamic>?
What am I doing wrong?
You should also await when getting the value and for that, you should declare the function getUserId() as Future and also return the function value like this:
static Future<int> getUserId() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getInt('userId') ?? 0;
}
var test = await AccountPreferences.getUserId(); // await inside here too, where you call it