Skip to content

Instantly share code, notes, and snippets.

@Mastersam07
Forked from Meghatronics/deviceInfo.service.dart
Created December 15, 2021 07:06
Show Gist options
  • Select an option

  • Save Mastersam07/31310d8e939fbf94c184dd102d92b05a to your computer and use it in GitHub Desktop.

Select an option

Save Mastersam07/31310d8e939fbf94c184dd102d92b05a to your computer and use it in GitHub Desktop.
Device Info Service
class DeviceInfoData {
final String deviceModel;
final String deviceId;
final String appVersion;
const DeviceInfoData(
{@required this.deviceModel,
@required this.deviceId,
@required this.appVersion});
}
class DeviceInfoService {
DeviceInfoData _deviceInfo;
final _deviceInfoPlugin = DeviceInfoPlugin();
DeviceInfoService._();
static final instance = DeviceInfoService._();
Future<DeviceInfoData> get data async {
if (_deviceInfo == null) {
_deviceInfo = await _getDeviceInfo();
}
return _deviceInfo;
}
Future<DeviceInfoData> _getDeviceInfo() async {
final packageInfo = await PackageInfo.fromPlatform();
final _androidInfo = await _deviceInfoPlugin.androidInfo;
final _iosDeviceInfo = await _deviceInfoPlugin.iosInfo;
final _versionNumber = packageInfo.version;
if (Platform.isAndroid) {
_deviceInfo = DeviceInfoData(
deviceModel: _androidInfo.model,
deviceId: _androidInfo.id,
appVersion: _versionNumber,
);
} else if (Platform.isIOS) {
_deviceInfo = DeviceInfoData(
deviceModel: _iosDeviceInfo.name,
deviceId: _iosDeviceInfo.identififerForVendor,
appVersion: _versionNumber,
);
} else {
_deviceInfo = DeviceInfoData(
deviceModel: "NA",
deviceId: "NA",
appVersion: _versionNumber,
);
}
return _deviceInfo;
}
}
/// So now you can do this in the header
Future<Map<String, String>> requestHeaders({bool useToken = true}) async {
final deviceInfoData = await DeviceInfoService.instance.data
//.... other code in the function
final headers = <String, String>{
'Content-Type': 'application/json',
'app-version': deviceInfoData.appVersion,
'phone-model': deviceInfoData.deviceModel,
'mobile-id': deviceInfoData.deviceId,
if (token != null && (useToken ?? true))
'Authorization': 'Bearer ${jsonDecode(token)}',
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment