Functions by file extension in Flutter - flutter

I’m using image picker package.
“https://pub.dev/packages/image_picker”
// Get from gallery
void ImgFromGallery() async {
final pickedFile = await picker.pickImage(source: ImageSource.gallery);
setState(() {
if (pickedFile != null) {
_proImage = File(pickedFile.path);
List<int> imageBytes = _proImage!.readAsBytesSync();
image = base64Encode(imageBytes);
print("_Proimage:$_proImage");
} else {
print('No image selected.');
}
});
}
It works, but if the user chooses a .gif format from his gallery, I want to run a different function. Can i check extension for selected file? If yes how can i do that? I’m new on Flutter.

File? _file;
String _imagePath = "";
bool imageAccepted;
takeImageFromGallery() async {
XFile? image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image!.path.endsWith("png")) {
imageAccepted = true;
} else if (image.path.endsWith("jpg")) {
imageAccepted = true;
} else if (image.path.endsWith("jpeg")) {
imageAccepted = true;
} else {
imageAccepted = false;
}
if (imageAccepted) {
if (image != null) {
setState(() {
_imagePath = image.path;
_file = File(_imagePath);
});
}
} else {
SnackBar(content: Text("This file extension is not allowed"));
}
}

You can use Path package like this:
import 'package:path/path.dart' as p;
final path = '/some/path/to/file/file.dart';
final extension = p.extension(path); // '.dart'

Related

how to run a stream in different thread in dart

Future<bool> checkConnection() async {
var connectivityResult = await (Connectivity().checkConnectivity());
bool connOk = false;
if (connectivityResult == ConnectivityResult.mobile) {
bool ii = await checkConnectionWithUrl();
if (ii == true) {
connOk = true;
}
} else if (connectivityResult == ConnectivityResult.wifi) {
bool ii = await checkConnectionWithUrl();
if (ii == true) {
connOk = true;
}
} else if (connectivityResult == ConnectivityResult.ethernet) {
bool ii = await checkConnectionWithUrl();
if (ii == true) {
connOk = true;
}
} else if (connectivityResult == ConnectivityResult.bluetooth) {
bool ii = await checkConnectionWithUrl();
if (ii == true) {
connOk = true;
}
} else {
connOk = false;
}
return connOk;
}
Future<bool> checkConnectionWithUrl() async {
bool response = false;
while (true) {
var checkin = await client.get(Uri.https('www.google.com', '/'));
if (checkin.statusCode == 200) {
response = true;
break;
} else {
sleep(const Duration(milliseconds: 500));
}
}
return response;
}
Stream checkStream() async* {
dynamic result = false;
while (true) {
try {
result = await checkConnection();
} catch (error) {
result = false;
} finally {
yield result;
}
await Future.delayed(const Duration(seconds: 1));
}
}
I am making a app. And I want to learn multi threading in dart. The above function what it will do is it look for wifi state every second and update the Ui. But when I run the function it will drop frams in ui. So I what to run it in a diffrent thread. can i do it.
---My main goal ---
I want to run this function in a different thread how do I do it

Stream<Position> of Geolocator.getPositionStream is not listen

I'm using geolocator and google_maps_flutter in my app to get user location, passing by getPositionStream.
The Map is the first screen of the app, and when I get user location it work fine, and the camera of the map zoom correctly.
But the user can login to his account, and it's recreated the Map. And my problem is here. When the login is done, my stream with my new location is not listen :/ I need to reload the app for that
My function in my viewModel
final Stream<Position>? stream = await _locationService.getLocation();
if (stream != null) {
stream.listen((location) async {
final newLocation =
CameraPosition(target: LatLng(location.latitude, location.longitude), zoom: 15);
if (controllerCompleter != null) {
final GoogleMapController controller = await controllerCompleter.future;
controller.animateCamera(CameraUpdate.newCameraPosition(newLocation));
}
});
}
In the locationService:
Future<Stream<Position>?> getLocation() async {
bool _serviceEnabled;
LocationPermission _permissionGranted;
_serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!_serviceEnabled) {
return null; // Use France's GPS coordinates by default
}
_permissionGranted = await Geolocator.checkPermission();
if (_permissionGranted == LocationPermission.denied) {
_permissionGranted = await Geolocator.requestPermission();
if (_permissionGranted == LocationPermission.denied ||
_permissionGranted == LocationPermission.deniedForever) {
return null; // Use France's GPS coordinates by default
} else {
return Geolocator.getPositionStream(locationSettings: locationSettings);
}
} else {
return Geolocator.getPositionStream(locationSettings: locationSettings);
}
}
If anyone have an idea of what I'm doing wrong.
Thanks in advance

Want to post geolocation on a external api using getx

I have already got the geolocation with longitude and latitude using the geolocation plugin with getx but now I want to post the same longitude and latitude on API with already present in the backhand the model is yet to be created and even the provider is also yet to be done and I don't know how and the location API post should run in the background once with the application opens up.
API body:-
{
"longitude":"55.5852",
"latitude":"77.6532"
}
Controller code:-
class RootController extends GetxController {
var latitude = 'Getting Latitude..'.obs;
var longitude = 'Getting Longitude..'.obs;
var address = 'Getting Address..'.obs;
final currentIndex = 0.obs;
final notificationsCount = 0.obs;
final customPages = <CustomPage>[].obs;
NotificationRepository _notificationRepository;
CustomPageRepository _customPageRepository;
StreamSubscription<Position> streamSubscription;
RootController() {
_notificationRepository = new NotificationRepository();
_customPageRepository = new CustomPageRepository();
}
#override
void onInit() async {
await getCustomPages();
getNotificationsCount();
if (Get.arguments != null && Get.arguments is int) {
changePageInRoot(Get.arguments as int);
} else {
changePageInRoot(0);
}
super.onInit();
getLocation();
}
#override
void onReady(){
super.onReady();
}
#override
void onClose(){
streamSubscription.cancel();
}
getLocation() async{
bool serviceEnabled;
LocationPermission permission;
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if(!serviceEnabled){
await Geolocator.openLocationSettings();
return Future.error('Location Services are disabled.');
}
permission = await Geolocator.checkPermission();
if(permission == LocationPermission.denied){
permission = await Geolocator.requestPermission();
if(permission == LocationPermission.denied){
return Future.error('Location permissions are denied');
}
}
if (permission == LocationPermission.deniedForever){
return Future.error('Location permissions are permanently denied');
}
streamSubscription = Geolocator.getPositionStream().listen((Position position) {
latitude.value = 'Latitude:${position.latitude}';
longitude.value = 'Longitude:${position.latitude}';
getAddressFromLatLang(position);
print(latitude.value);
print(longitude.value);
});
}
Future<void> getAddressFromLatLang(Position position)async{
List<Placemark> placemark = await
placemarkFromCoordinates(position.latitude,position.longitude);
Placemark place = placemark[0];
address.value = 'address:${place.locality},${place.country}';
}
List<Widget> pages = [
HomeView(),
// EServicesView2(),
ReviewsView(),
MessagesView(),
AccountView(),
];
Widget get currentPage => pages[currentIndex.value];
/**
* change page in route
* */
void changePageInRoot(int _index) {
currentIndex.value = _index;
}
void changePageOutRoot(int _index) {
currentIndex.value = _index;
Get.offNamedUntil(Routes.ROOT, (Route route) {
if (route.settings.name == Routes.ROOT) {
return true;
}
return false;
}, arguments: _index);
}
Future<void> changePage(int _index) async {
if (Get.currentRoute == Routes.ROOT) {
changePageInRoot(_index);
} else {
changePageOutRoot(_index);
}
await refreshPage(_index);
}
Future<void> refreshPage(int _index) async {
switch (_index) {
case 0:
{
await Get.find<HomeController>().refreshHome();
break;
}
case 2:
{
await Get.find<MessagesController>().refreshMessages();
break;
}
}
}
void getNotificationsCount() async {
notificationsCount.value = await _notificationRepository.getCount();
}
Future<void> getCustomPages() async {
customPages.assignAll(await _customPageRepository.all());
}
}
what else should I do?

i cannot stop/pause a song in audioplayers

I am using the audioplayers plugin in my code.
I can play audio but I cannot stop/pause audio. Following is a function that I use to play/stop the audio.
Future<void> onPlay({#required filepath, #required index}) async {
AudioPlayer audioPlayer = AudioPlayer(mode: PlayerMode.MEDIA_PLAYER);
if (!_isPlaying) {
int result = await audioPlayer.play(filepath, isLocal: true);
if (result == 1) {
setState(() {
_isPlaying = true;
_selectedIndex = index;
});
}
} else {
int result = await audioPlayer.stop();
if (result == 1) {
setState(() {
_isPlaying = false;
});
}
}
}
}
You're instantiating a new AudioPlayer audioPlayer object each time you call onPlay, which leaves you unable to stop that same player later.
Store your AudioPlayer audioPlayer in the state somewhere.
AudioPlayer audioPlayer = AudioPlayer(mode: PlayerMode.MEDIA_PLAYER);
Future<void> onPlay({#required filepath, #required index}) async {
if (!_isPlaying) {
int result = await audioPlayer.play(filepath, isLocal: true);
if (result == 1) {
setState(() {
_isPlaying = true;
_selectedIndex = index;
});
}
} else {
int result = await audioPlayer.stop();
if (result == 1) {
setState(() {
_isPlaying = false;
});
}
}
}

Problem in storing LocationData in flutter

I am trying getting the location coordinates of user and storing it in variable.
I use the location library from flutter.
But I get this error:
type 'Future' is not a subtype of type 'Future'
This is my code
Future<LocationData> coords;
double lat, long;
coords = getUserLocationCoordinates();
coords.then((value) => {
lat = value.latitude,
long = value.longitude,
});
My getUserLocationCoordinates function
getUserLocationCoordinates() async {
LocationData currentLocation;
String error;
Location location = Location();
try {
currentLocation = await location.getLocation();
} on PlatformException catch (e) {
if (e.code == 'PERMISSION_DENIED') {
error = 'please grant permission';
print(error);
}
if (e.code == 'PERMISSION_DENIED_NEVER_ASK') {
error = 'permission denied- please enable it from app settings';
print(error);
}
currentLocation = null;
}
return currentLocation;
}
Any help is greatly appreciated
Initialize variables
String latitude_data;
String longitude_data;
bool _serviceEnabled;
Current Location Function
Future _getLocation() async {
Location location = new Location();
var _permissionGranted = await location.hasPermission();
_serviceEnabled = await location.serviceEnabled();
if (_permissionGranted != PermissionStatus.granted || !_serviceEnabled) {
_permissionGranted = await location.requestPermission();
_serviceEnabled = await location.requestService();
} else {
///Do something here
}
LocationData _currentPosition = await location.getLocation();
longitude_data=_currentPosition.longitude.toString();
latitude_data=_currentPosition.latitude.toString();
///if you want you can save data to sharedPrefrence
SharedPrefrence().setLatitude(_currentPosition.latitude.toString());
SharedPrefrence().setLongitude(_currentPosition.longitude.toString());
}