I have this problem is that in flutter I notice there is not able to operate or use the traditional bluetooth as there is no any library supporting it. I have tested flutter_blue-master etc. So then I saw that it can behave as beacon. So I have used the codes below. For android I just set
Region(
identifier: 'com.example.myDeviceRegion',)); its able to work. So the same I set in IOS its not able to work? So what is best workaround for blueetooth in flutter? I am using this package flutter_beacon. For the beacon broadcasting I am using this package beacon_broadcast.
initScanBeacon() async {
await flutterBeacon.initializeScanning;
await checkAllRequirements();
if (!authorizationStatusOk ||
!locationServiceEnabled ||
!bluetoothEnabled) {
print('RETURNED, authorizationStatusOk=$authorizationStatusOk, '
'locationServiceEnabled=$locationServiceEnabled, '
'bluetoothEnabled=$bluetoothEnabled');
return;
}
/*final regions = <Region>[
Region(
identifier: 'com.example.myDeviceRegion',
),
];*/
final regions = <Region>[];
regions.add(Region(
identifier: 'com.example.myDeviceRegion',
minor: 100,
major: 1));
if (_streamRanging != null) {
if (_streamRanging.isPaused) {
_streamRanging.resume();
return;
}
}
_streamRanging =
flutterBeacon.monitoring(regions).listen((MonitoringResult result) {
print(result);
if (result != null && mounted) {
print("GOT RESTULT READY");
setState(() {
//_regionBeacons[result.region] = result.region;
_beacons.clear();
print("List value is json"+result.toJson.toString());
_regionBeacons.values.forEach((list) {
print("List value is");
_beacons.addAll(list);
print("after Beacon size now is "+_beacons.length.toString());
});
//_beacons.sort(_compareParameters);
print("Beacon size now is "+_beacons.length.toString());
});
}
});
}
A few things to check:
Make sure your Region definition has a proximityUUID value. I am surprised that it works even on Android without this. On iOS it certainly won't work at all -- iOS requires a beacon proximityUUID be specified up front in order to detect. The value you give for the prximityUUID must exactly match what your beacon is advertising or you won't see it.
Make sure you have gone through all the iOS setup steps here: https://pub.dev/packages/flutter_beacon
Be extra sure that you have granted location permission to your iOS app. You can go to Settings -> Your App Name to check if location permission is granted.
Make sure bluetooth is enabled in settings for the phone
Make sure location is enabled in settings for the phone
https://pub.dev/packages/flutter_beacon
There's an update on GitHub but was yet to push to pub.dev previously.
Do update to 0.5.0.
Always check pub.dev for updates. or github reported issues.
Related
I want to get a device id or any unique number that can not be changed when someone uninstalls the app. This device is for both android and iOS and is in the flutter framework. I want this to manage my device management.
Thanks for the help.
I tried some of the most commonly used packages in flutter like device_info_plus and flutter_udid but IDs generated from these changes every day.
Did you tried platform_device_id
This package can help you to get deviceId in android, iOS, windows, macOS and even in web and linux.
After importing the package you need to use following code
try {
deviceId = await PlatformDeviceId.getDeviceId;
} on PlatformException {
deviceId = 'Failed to get deviceId.';
}
You can use #Rohan's answer also. platform_device_id package. Read more
There is guide for device_info_plus package Read more
add package to your flutter project.
Create a method like this:
Future<String> getUniqueDeviceId() async {
String uniqueDeviceId = '';
var deviceInfo = DeviceInfoPlugin();
if (Platform.isIOS) {
var iosDeviceInfo = await deviceInfo.iosInfo;
uniqueDeviceId =
'${iosDeviceInfo.name}:${iosDeviceInfo.identifierForVendor}'; //
unique ID on iOS
} else if(Platform.isAndroid) {
var androidDeviceInfo = await deviceInfo.androidInfo;
uniqueDeviceId =
'${androidDeviceInfo.name}:${androidDeviceInfo.id}' ; // unique ID
on Android
}
return uniqueDeviceId;
}
use it like this:
String deviceId = await getUniqueDeviceId();
Note (updateded):
Don't use androidDeviceInfo.androidId. This would change when your mac address changes. Mobile devices above Android OS 10/11 will generate a randomized MAC. This feature is enabled by default unless disabled manually. This would cause the androidId to change when switiching networks. You can confirm this by yourself by changing androidDeviceInfo.id to androidDeviceInfo.androidId above.
(Got details from #Ariel)
I am trying to get wifi ssid in flutter for ios(13+) with connectivity plugin but result returns null. I have added access wireless information from Xcode but still not working. Can anyone help out please?
Future<void> _updateConnectionStatus(ConnectivityResult result) async{
switch(result){
case ConnectivityResult.wifi:
String wifiName;
try {
if (Platform.isIOS) {
LocationAuthorizationStatus status =
await _connectivity.getLocationServiceAuthorization();
if (status == LocationAuthorizationStatus.notDetermined) {
print('wifiName notDetermined: ');
status = await _connectivity.requestLocationServiceAuthorization();
}
if (status == LocationAuthorizationStatus.authorizedAlways ||
status == LocationAuthorizationStatus.authorizedWhenInUse) {
print('wifiName authorizedWhenInUse: ');
wifiName = await _connectivity.getWifiName();
setState(() {
_ssid = wifiName != null ? wifiName : _ssid;
});
} else {
print('wifiName ,.,.,.,: ');
wifiName = await _connectivity.getWifiName();
}
} else {
LocationAuthorizationStatus status =
await _connectivity.getLocationServiceAuthorization();
// if(status == )
wifiName = await _connectivity.getWifiName();
print('android wifi');
print(wifiName);
}
} on PlatformException catch (e) {
print(e.toString());
wifiName = "Failed to get Wifi Name";
}
setState(() {
_connectionStatus ='result '+ '$result\n'
'Wifi Name: $wifiName\n';
print('_connectionStatus $_connectionStatus');
});
break;
case ConnectivityResult.mobile:
Fluttertoast.showToast(msg: 'Connected to mobile network');
break;
case ConnectivityResult.none:
Fluttertoast.showToast(msg: 'Connected to no network');
setState(() => _connectionStatus = result.toString());
break;
default:
setState(() => _connectionStatus = 'Failed to get connectivity.');
break;
}
}
I have tried with above code from connectivity plugin example. Also there is showing 'As of iOS 13, Apple announced that these APIs will no longer return valid information'. So how to achieve my goal?
In 2020, the flutter team decided to create a new plugin for wifi information, removing these methods from the connectivity plugin.
So check the network_info_plus plugin: the method signatures are just the same.
As on being able to access this on iOS 13+, according to the package's readme:
The CNCopyCurrentNetworkInfo will work for Apps that:
The app uses Core Location, and has the user’s authorization to use
location information.
The app uses the NEHotspotConfiguration API to configure the current
Wi-Fi network.
The app has active VPN configurations installed.
If your app falls into the last two categories, it will work as it is.
If your app doesn't fall into the last two categories, and you still
need to access the wifi information, you should request user's
authorization to use location information.
There is a helper method provided in this plugin to request the
location authorization: requestLocationServiceAuthorization. To
request location authorization, make sure to add the following keys to
your Info.plist file, located in /ios/Runner/Info.plist:
NSLocationAlwaysAndWhenInUseUsageDescription - describe why the app
needs access to the user’s location information all the time
(foreground and background). This is called Privacy - Location Always
and When In Use Usage Description in the visual editor.
NSLocationWhenInUseUsageDescription - describe why the app needs
access to the user’s location information when the app is running in
the foreground. This is called Privacy - Location When In Use Usage
Description in the visual editor.
So basically, from iOS13 on, you have to request the user's permission for location - it actually makes sense.
I am quite new to Flutter, and I am currently working on an application that needs barcode reading. So I used the barcode_scan library, and I am now able to get the barcode number from a scanned barcode.
To be clear, I am not asking how to scan a barcode / get the barcode number.
My question is: how can I get more information about a product from its barcode number in Flutter (e.g. product name)? Can I do this from the barcode_scan library, or will I need something else?
Edit: Forgot to mention, when scanning QR codes I am able to get the information it encodes (e.g. product name or URL), but this is not the case with barcodes.
My current (relevant) code is as follows:
String result = 'Hey there!';
Future scanBarcode() async {
if(await Permissions.checkCameraPermission()) {
try {
await BarcodeScanner.scan().then((scan_result) {
//here scan_result is the obtained barcode number
setState(() { result = scan_result; });
});
}
//handling exceptions...
}
else {
setState(() { result = 'Camera permission denied'; });
}
}
(Side note, here Permissions.checkCameraPermission() is a function I created to check if camera permission is granted, shouldn't be relevant for the question).
I'm using the same plugin for scanning barcode or qr code for my flutter app..
String result = 'Hey there!';
Future scanBarcode() async {
if(await Permissions.checkCameraPermission()) {
try {
// I get the scan result from BarcodeScanner this way and it is working for me.
result = await BarcodeScanner.scan();
}
//handling exceptions...
}
else {
setState(() { result = 'Camera permission denied'; });
}
}
Well, it seems the only plausible way to do it from Flutter would be to use a barcode lookup API like #RichardHeap proposed in the comments. If my app was Flutter only (without a backend server connected to it) I believe I would have gone that way.
But I guess I'll just send the barcode number itself to the backend and deal with it on the server-side.
What I understand is, on scanning the code, you need the information / data about the product.
If I understood it right, there are several aggregators of the barcode. You can get APIs from them. But there is not single place from where you get all the information.
https://yourstop.info is a PWA. When I run lighthouse on it, the PWA score comes up as 73 and performance as 60, see image below.
It is giving a time to interactive of 19.1 seconds which is the reason for the low scoring. What happens on startup is that when the user's location is determined, a list of relevant bus stops is downloaded in the background. The code for this is
var firstLocationUpdate = false;
//var firstLocationUpdate = true;
if (navigator.geolocation) {
navigator.geolocation.watchPosition(updatePosition, showError, geoOptions);
}
else {
window.ys.userLocationError = "Geolocation is not supported by this browser";
}
function updatePosition(position) {
if (position != null) {
window.ys.userLat = position.coords.latitude;
window.ys.userLon = position.coords.longitude;
try {
// When google maps was not loaded this was throwing an exception
window.ys.userLocation = new google.maps.LatLng(window.ys.userLat, window.ys.userLon);
}
catch (e) {
console.log("Google maps not loaded when initializing geo.js, userLocation LatLng not set");
}
window.ys.userLocationError = "";
if (window.ys.userLocation != null && window.ys.userLocationTripMarker != null) {
window.ys.userLocationTripMarker.setPosition(window.ys.userLocation);
}
if (window.ys.userLocation != null && window.ys.userLocationSearchMarker != null) {
window.ys.userLocationSearchMarker.setPosition(window.ys.userLocation);
}
if (firstLocationUpdate == false) {
var event = document.createEvent("HTMLEvents");
event.initEvent('firstlocationupdate', true, true);
document.dispatchEvent(event);
firstLocationUpdate = true;
}
}
}
This does however not impact at all on the readiness of the PWA, the page is already fully rendered and the user can perform other tasks while the background function is in progress. If in the code snippet above, firstLocationUpdate is initialized to true and the background download is prevented, then the lighthouse scoring is much higher as shown here
Both cases however show the exact same user experience as far as I can tell. But the benefit of doing the background stop download is that the Locate the Nearest Stops operation happens much quicker.
The problem with the lower score for PWA is that chrome no longer automatically display the web app install banner. So I am in a situation where I need to make a choice and my current preference is for the background download to occur.
So the question is, is there a workaround which will allow me to have BOTH a high PWA score AND do the background download ?
Or is there any way of influencing how lighthouse scores PWAs, in my eyes anyway the background download resulting is lighthouse lengthening the time to interactive is not correct behavior ?
Is it possible to show users of your extension or color theme notifications in Visual Studio Code? For someone who has my color theme or extension installed and is getting updates, I would like to possibly show this person a notification after they update the extension (That could be on launch of VSCode, or right after they go into the market to update & reload the extension and client themselves.)
For example: I think it would be beneficial to me and not invasive if they saw a notification after updating the extension saying "Feedback? Suggestions? Fixes?..on the theme?" OR notifying them of something changed in the theme that may not be favorable. So they can "opt out" of that change if they want (Like an extra set of borders around something or the color change of something.)
Obviously people with all notifications off would not be affected, but I thought an occasional notification after a rare update wouldn't be too bad. I have not been able to find info on if this is possible, and if it was, how to do it. Any info on this is appreciated. And if it is possible, those reading this, whether you've done it or not, would you recommend showing a notification to your theme users in that way?
Thanks :)
Show a notification on bottom-right corner, whenever your extension is updated. You can also control to show it only for major/minor releases.
That's how it looks:
Add below code to extension.ts:
import { window, ExtensionContext, extensions, env, Uri } from "vscode";
const extensionId = "jerrygoyal.shortcut-menu-bar";
// this method is called when your extension is activated
export function activate(context: ExtensionContext) {
showWhatsNew(context); // show notification in case of a major release i.e. 1.0.0 -> 2.0.0
}
// https://stackoverflow.com/a/66303259/3073272
function isMajorUpdate(previousVersion: string, currentVersion: string) {
// rain-check for malformed string
if (previousVersion.indexOf(".") === -1) {
return true;
}
//returns int array [1,1,1] i.e. [major,minor,patch]
var previousVerArr = previousVersion.split(".").map(Number);
var currentVerArr = currentVersion.split(".").map(Number);
if (currentVerArr[0] > previousVerArr[0]) {
return true;
} else {
return false;
}
}
async function showWhatsNew(context: ExtensionContext) {
const previousVersion = context.globalState.get<string>(extensionId);
const currentVersion = extensions.getExtension(extensionId)!.packageJSON
.version;
// store latest version
context.globalState.update(extensionId, currentVersion);
if (
previousVersion === undefined ||
isMajorUpdate(previousVersion, currentVersion)
) {
// show whats new notificatin:
const actions = [{ title: "See how" }];
const result = await window.showInformationMessage(
`Shortcut Menubar v${currentVersion} — Add your own buttons!`,
...actions
);
if (result !== null) {
if (result === actions[0]) {
await env.openExternal(
Uri.parse(
"https://github.com/GorvGoyl/Shortcut-Menu-Bar-VSCode-Extension#create-buttons-with-custom-commands"
)
);
}
}
}
}
You can see this implementation in my VSCode extension repo Shortcut Menu Bar
I think you can register the version during activation event and check for it on each activation. Then you can do whatever you want. For instance GitLens is migrating settings https://github.com/eamodio/vscode-gitlens/blob/master/src/extension.ts#L52 and i'm pretty sure I remember that they were opening a notification (but i have not found immediately in the code)
regards,