Function returns Future<dynamic> - flutter

So I'm learning flutter and I have a function which returns a UserLocation object -
getUserLocation() async {
bool _serviceEnabled;
loc.PermissionStatus _permissionGranted;
_serviceEnabled = await location.serviceEnabled();
if (!_serviceEnabled) {
_serviceEnabled = await location.requestService();
if (!_serviceEnabled) {
return;
}
}
_permissionGranted = await location.hasPermission();
if (_permissionGranted == loc.PermissionStatus.denied) {
_permissionGranted = await location.requestPermission();
if (_permissionGranted != loc.PermissionStatus.granted) {
return;
}
}
try {
_currentPosition = await location.getLocation();
} catch (e) {
print(e);
}
List<geo.Placemark> placemarks = await geo.placemarkFromCoordinates(
_currentPosition.latitude ?? 0, _currentPosition.longitude ?? 0);
var countryNameList = placemarks[0].country?.split(' ');
if (countryNameList!.isNotEmpty && countryNameList.length >= 2) {
for (var eachLetter in countryNameList) {
abbr += eachLetter[0];
}
} else {
abbr = countryNameList.toString().substring(0, 2).toUpperCase();
}
return UserLocation(
city: placemarks[0].locality ?? 'Chennai',
country: abbr,
latitude: _currentPosition.latitude,
longitude: _currentPosition.longitude);
}
Now, when I'm calling this function, It says that It returns Future<dynamic)..Future because it's an async function and dynamic because it doesn't really return anything if location.ServiceEnabled or location.hasPermission fails.
Anyways, the point is that I want to access the UserLocation object returned by this method whenever I'm calling this function from somewhere else but It always say that this function returns Future. How I can do that?? Any idea?

This should solve the problem, Set the return type of getUserLocation() function to Future<UserLocation?> and return null wherever there is nothing to return.

Related

Flutter: PlatformException (PlatformException(, cannot find the file, null, null)) on FlutterAudioRecorder2

class AudioRecorder {
static DateTime now = DateTime.now();
static String timestamp = now.toString();
var recorder = FlutterAudioRecorder2("./file_path",
audioFormat: AudioFormat.AAC);
// or var recorder = FlutterAudioRecorder2("file_path.mp3");
startRecording() async {
await recorder.initialized;
await recorder.start(); // <- error here
}
stopRecording() async {
var result = await recorder.stop();
}
}
I can't find a way to fix , mainly because I don't understand what does it means, why it says "cannot find the file" but the file needs to be created? (since it's a recording?)
Few points I noticed are
Please check if its initialised or not in the initstate
await recorder.initialized;
//after initialisation add this
var current = await recorder.current(channel: 0);
//you should get the current status as initialised if its done properly.
then on start recording use
await recorder.start()
Also make sure that the file path is right
Edit
This is the code to init the recorder
_init() async {
try {
bool hasPermission = await FlutterAudioRecorder2.hasPermissions ?? false;
if (hasPermission) {
String customPath = '/flutter_audio_recorder_';
io.Directory appDocDirectory;
// io.Directory appDocDirectory = await getApplicationDocumentsDirectory();
if (io.Platform.isIOS) {
appDocDirectory = await getApplicationDocumentsDirectory();
} else {
appDocDirectory = (await getExternalStorageDirectory())!;
}
// can add extension like ".mp4" ".wav" ".m4a" ".aac"
customPath = appDocDirectory.path + customPath + DateTime.now().millisecondsSinceEpoch.toString();
_recorder = FlutterAudioRecorder2(customPath, audioFormat: AudioFormat.AAC);
await _recorder!.initialized;
// after initialization
var current = await _recorder!.current(channel: 0);
print(current);
// should be "Initialized", if all working fine
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("You must accept permissions")));
}
} catch (e) {
print(e);
}
}

Dart the operator [] isn't defined for 'Future<Map<String,Object>> Function(String)'

I'm trying to set up Auth0 for my Flutter app from this demo, but I ran into this issue. I've only been using Flutter for a little while, and I fixed a few errors, but can't fix this one. I checked for other answers here, and tried the documentation too. The error message is;
The operator [] isn't defined for 'Future<Map<String,Object>> Function(String)'
This is the method with the error;
Future<void> loginAction() async {
setState(() {
isBusy = true;
errorMessage = '';
});
try {
final AuthorizationTokenResponse? result =
await appAuth.authorizeAndExchangeCode(
AuthorizationTokenRequest(
AUTH0_CLIENT_ID,
AUTH0_REDIRECT_URI,
issuer: 'https://$AUTH0_DOMAIN',
scopes: ['openid', 'profile', 'offline_access'],
promptValues: ['login']
),
);
Map<String, Object> parseIdToken(String idToken) {
final parts = idToken.split(r'.');
assert(parts.length == 3);
return jsonDecode(
utf8.decode(base64Url.decode(base64Url.normalize(parts[1]))));
}
Future<Map<String, Object>> getUserDetails(String accessToken) async {
final url = 'https://$AUTH0_DOMAIN/userinfo';
final response = await http.get(Uri.parse(
url,
));
if (response.statusCode == 200) {
return jsonDecode(response.body);
} else {
throw Exception('Failed to get user details');
}
}
await secureStorage.write(
key: 'refresh_token', value: result!.refreshToken);
setState(() {
isBusy = false;
isLoggedIn = true;
name = parseIdToken['name'];
picture = getUserDetails['picture'];
});
} catch (e, s) {
print('login error: $e - stack: $s');
setState(() {
isBusy = false;
isLoggedIn = false;
errorMessage = e.toString();
});
}
}
And the lines that are erroring are;
name = parseIdToken['name'];
picture = getUserDetails['picture'];
Can this be fixed?
getUserDetails is a function, and so it doesn't have a [] operator.
Instead, try: var userDetails = await getUserDetails("token..."); picture = userDetails["picture"];

If statement is being registered as a variable in my Dart Flutter code? How do I change this?

The highlighted text in the image is giving me errors like those shown in my Problems console. I've never receieved these kinds of issues when dealing with if statements, and I'm wondering why they are no registering as if statements. In one of the errors it says "if is already defined", but its not a variable. How do I solve this? Does it have anything to do with the async functions? I struggled with these
I am trying to request the user location data for a map I plan to implement in a flutter App, but it's not working :/ SOMETHING is wrong with my ifs that I can't solve.
Future<bool> assignService(Location loc) async {
bool servicestatus = await loc.serviceEnabled();
return servicestatus;
}
Future<PermissionStatus> assignPermission(Location loc) async {
return await loc.hasPermission();
}
Future<LocationData> assignLocation(Location loc) async {
return await loc.getLocation();
}
Location location = new Location();
var _serviceEnabled = assignService(location);
if (_serviceEnabled != true) {
_serviceEnabled = assignService(location);
if (!_serviceEnabled) {
return;
}
}
var _permissionGranted = assignPermission(location);
if (_permissionGranted == PermissionStatus.denied) async{
_permissionGranted = await location.requestPermission();
if (_permissionGranted != PermissionStatus.granted) {
return;
}
}
var _locationData = assignLocation(location);
Update (code before that above):
Future<bool> assignService(Location loc) async {
bool servicestatus = await loc.serviceEnabled();
return servicestatus;
}
Future<PermissionStatus> assignPermission(Location loc) async {
return await loc.hasPermission();
}
Future<LocationData> assignLocation(Location loc) async {
return await loc.getLocation();
}
Location location = Location();
var _serviceEnabled = assignService(location);
var _permissionGranted = assignPermission(location);
You wrote code outside a function.
Only variable declaration can be outside a function, not code.
For example you can do :
void StartService() {
if (_serviceEnabled != true) {
_serviceEnabled = assignService(location);
if (!_serviceEnabled) {
return;
}
if (_permissionGranted == PermissionStatus.denied) async{
_permissionGranted = await location.requestPermission();
if (_permissionGranted != PermissionStatus.granted) {
return;
}
}
}
The if shouldn't be outside code block.
You have to put it in a function. That's explain your error.
Tell me if you need more details.
Edit : just for information, the "new" keyword is not needed in flutter anymore.
Solution is very simple if can't be the member of a class you should do if checks inside a function.
void doIfChecks(){
// if statements
}
Hope this will help you.

NoSuchMethodError the method was called on Null

in this code below WeatherModel tried to get current location of android phone,
my problem here is once I start runing it show NoSuchMethod Found, and it says reciever is null,
as I tried a lot of debugging just to see where is my problem.
I now understand that my problem is when I create instance of Location() in WeatherModel, longitude and latitude are null, it never gets value and I dont know why...
Sorry for my bad english :(
const apiKey = 'e3653190f2b1d4803287b3074ecfe618';
const apiWeatherURL = 'https://api.openweathermap.org/data/2.5/weather';
class WeatherModel {
Future<dynamic> getLocationWeather() async {
Location location = Location();
NetworkHelper networkHelper = NetworkHelper(
'https://api.openweathermap.org/data/2.5/weather?lat=${location.latitude}&lon=${location.longitude}&appid=$apiKey');
var weatherData = networkHelper.getData();
return weatherData;
}
}
.....
class Location {
double latitude;
double longitude;
Future<void> getCurrentLocation() async {
try {
Position _position = await Geolocator()
.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
longitude = _position.longitude;
print(longitude);
latitude = _position.latitude;
print(latitude);
} catch (e) {
print(e);
}
}
}
.........
class NetworkHelper {
NetworkHelper(this.url);
final url;
Future getData() async {
http.Response response = await http.get(url);
if (response.statusCode == 200) {
var data = jsonDecode(response.body);
print(" Sarkawtua $data");
return data;
} else
print("Error ${response.statusCode} keshay Internet");
}
}
Because you instance fields are not updated, so they are null. You have method for getting current location but it's not fired in getLocationWeather.
Future<dynamic> getLocationWeather() async {
Location location = Location();
await location.getCurrentLocation();
NetworkHelper networkHelper = NetworkHelper(
'https://api.openweathermap.org/data/2.5/weather?lat=${location.latitude}&lon=${location.longitude}&appid=$apiKey');
var weatherData = await networkHelper.getData();
return weatherData;
}
Edit: You also must await networkHelper.getData() method to get not Future Object.

Flutter Future always return null

What is wrong in my code it always returns null
getLocation().then((r) {
if (r != null) {
print("r=" + r.length.toString());
} else {
print("result is null");
}
});
Future< List<double>> getLocation() async {
// print("getLocation called");
location = new Location();
List<double> result=[];
location.getLocation().then((loc) {
result.add(loc.latitude);
result.add(loc.longitude);
result.add(4213);
// print(loc.latitude.toString() + "," + loc.longitude.toString() +" l="+l1.length.toString());
return result;
}).catchError((e){
return result;
});
}
You are not returning anything in your function, only in your then callback.
Since you are using async syntax anyway you can just go for:
Future< List<double>> getLocation() async {
location = new Location();
List<double> result=[];
var loc = await location.getLocation();
result.add(loc.latitude);
result.add(loc.longitude);
result.add(4213);
return result;
}
I've taking error handling out of the code but you can just use try-catch if you want that.