Flutter SDK not found in Android Studio + MacOS - flutter

Whenever i try to run my flutter app on Android Studio, this error message pop up:
FAILURE: Build failed with an exception.
* Where:
Build file '/Users/max/Projects/Flutter/myapp/android/app/build.gradle' line: 11
* What went wrong:
A problem occurred evaluating project ':app'.
> Flutter SDK not found. Define location with flutter.sdk in the local.properties file.
these are the first lines of said build.gradle file
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('key.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new FileNotFoundException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
I got it working on XCode.
The real problem is that i have installed flutter in that very folder, and i have 0 issue when i run flutter doctor -v.
After some googling i have found some answers but they were not useful because all of them had me verify
A - the flutter SDK path as per following image:
B - my myapp/android/local.properties file, which is as follows
sdk.dir=/Users/max/Library/Android/sdk
flutter.sdk=/Users/max/SDKs/flutter
flutter.buildMode=debug
flutter.versionName=1.0.0
flutter.versionCode=1
C - my modules dependency
does anyone know what is going on? it's been 2 weeks and i haven't figured this out yet.
thanks in advance.

Related

Flutter get android screen DPI inside fragment activity?

I have a flutter activity which gets screen DPI which works fine, but i need to make it a FlutterFragmentActivity because i need to use local_auth plugin inside the app, i've tried something like this:
class MainActivity: FlutterFragmentActivity() {
// Native android channel used to get the screen DPI.
// Using a lot of code from the flutter docs: https://docs.flutter.dev/development/platform-integration/platform-channels?tab=android-channel-kotlin-tab
private val CHANNEL = "screenDimensions"
override fun configureFlutterEngine(#NonNull flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
// Note: this method is invoked on the main thread.
call, result ->
if(call.method == "getScreenDPI") {
val screenDPI = getScreenDPI()
result.success(screenDPI)
}
else {
result.notImplemented()
}
}
}
// Code from
// https://stackoverflow.com/a/15699681
private fun getScreenDPI(): Double {
val w = activity.windowManager
val d: Display = w.defaultDisplay
val metrics = DisplayMetrics()
d.getMetrics(metrics)
val dpi = metrics.densityDpi
return dpi.toDouble();
}
}
but now it doesn't recognize activity anymore and throws this exception: `MainActivity.kt: (39, 17): Unresolved reference: activity
FAILURE: Build failed with an exception.
What went wrong:
Execution failed for task ':app:compileDebugKotlin'.
A failure occurred while executing org.jetbrains.kotlin.compilerRunner.GradleCompilerRunnerWithWorkers$GradleKotlinCompilerWorkAction
Compilation error. See log for more details`
Does anyone know how to keep the getDPI working and enable local_auth at the same time?
Any help appreciated.

Unity3D firebase AUTH not working on ANDROID fierbase doesnt connect or something

in editor work fine. i am trying to add my project fierbase and in work. but when i start test at android login window dont react. i am trying to do this
Unity3D firebase AUTH not working on ANDROID
public class FirebaseINIT : MonoBehaviour
{
public static bool firebaseReady;
void Start()
{
CheckIfReady();
}
void Update()
{
if(firebaseReady == true)
{
SceneManager.LoadScene("LoginScene");
}
}
public static void CheckIfReady()
{
Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task => {
Firebase.DependencyStatus dependencyStatus = task.Result;
if (dependencyStatus == Firebase.DependencyStatus.Available)
{
Firebase.FirebaseApp app = Firebase.FirebaseApp.DefaultInstance;
firebaseReady = true;
Debug.Log("Firebase is ready for use.");
}
else
{
firebaseReady = false;
UnityEngine.Debug.LogError(System.String.Format(
"Could not resolve all Firebase dependencies: {0}", dependencyStatus));
}
});
}
}
but not loaded next scene. and i am confused why this happen, i cant do next because dont understand problem. May this will be from android resolve? Because in order to build the project, I must remove the Resolved libraries.
otherwise if I don't remove assets=> Android=> resolve libraries then I will get the following errors
Configure project :launcher
WARNING: The option setting 'android.enableR8=false' is deprecated.
Execution failed for task ':launcher:processReleaseResources'.
A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
Android resource linking failed
the project has an additional plugin for advertising appodeal + admob at least the direction of movement of the study of the issue
and i am integrate this first time i am not sure i am at the right way

Does not allow to save image to local directory in flutter in android 10

I'm trying to save an image to phone local directory. Here I use image_downloader package for that. Here's my code
class DownloadImage {
Future writeToDownloadPath(GridImage imageData) async {
try {
var imageId = await ImageDownloader.downloadImage(imageData.url
,destination: AndroidDestinationType.custom(directory: 'motivational Quotes',
inPublicDir: true ,subDirectory: '/motivational Quotes${imageData.location}'));
print('imageId' + imageId.toString());
if (imageId == null) {
return;
}
} catch(e) {
print(e.toString());
}
}
}
When I run on Android 10 device and try to download an image it gives me this error,
E/MethodChannel#plugins.ko2ic.com/image_downloader(25282): java.lang.IllegalStateException: Not one of standard directories: motivational Quotes
I already added android:requestLegacyExternalStorage="true" in AndroidManifest and set targetSdkVersion and compileSdkVersion to 29 in build.gradle file. I did flutter clean and run the code but issue remain the same.
build.gradle
defaultConfig {
applicationId "com.example.app
minSdkVersion 21
targetSdkVersion 29
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
multiDexEnabled true
}
AndroidManifest
<application
android:name="io.flutter.app.FlutterApplication"
android:label="Motivational Quotes"
android:icon="#mipmap/ic_launcher"
android:requestLegacyExternalStorage="true">
I would be really grateful if anyone can help me with this issue. Thanks !
I faced the same issue with Android 10, I think the feature of saving in custom directory is not compatible with Android10 . The same code works perfectly for others
There are only 4 standard directories in this package.
/// Environment.DIRECTORY_DOWNLOADS
static final directoryDownloads =
AndroidDestinationType._internal("DIRECTORY_DOWNLOADS");
/// Environment.DIRECTORY_PICTURES
static final directoryPictures =
AndroidDestinationType._internal("DIRECTORY_PICTURES");
/// Environment.DIRECTORY_DCIM
static final directoryDCIM =
AndroidDestinationType._internal("DIRECTORY_DCIM");
/// Environment.DIRECTORY_MOVIES
static final directoryMovies =
AndroidDestinationType._internal("DIRECTORY_MOVIES");
So, you have to change here:
var imageId = await ImageDownloader.downloadImage(imageData.url
,destination: AndroidDestinationType.custom(directory: 'motivational Quotes',
inPublicDir: true ,subDirectory: '/motivational Quotes${imageData.location}'));
I advise you to keep it simple like this:
destination: AndroidDestinationType.directoryPictures
..inExternalFilesDir()
..subDirectory('${imageData.location}'),

Plugin project :location_web not found. Please update settings.gradle. How do I fix this?

I was using the google maps api and location pub,dev package in my android flutter app, and tried to bring up an image using the url from the api.
This was the url with some code:
class LocationHelper{
static String mapviewpointer({double latitude, double longitude}){
return "https://maps.googleapis.com/maps/api/staticmap?center=$latitude,$longitude&zoom=13&size=600x300&maptype=roadmap&markers=color:pink%7Clabel:C%7C$latitude,$longitude&key=$GOOGLE_API_KEY";
}
}
it threw the following error message:
Plugin project :location_web not found. Please update settings.gradle;
I'm not sure how to fix this error.
This was the other error I received in my terminal:
I/flutter (21880): Invalid argument(s): No host specified in URI file:///Instance%20of%20'Future%3CString%3E'
The Area in which I get the error message above is here in my code:
Future <String> _getUserLocation() async{
final locData = await Location().getLocation();
final staticMapUrl = LocationHelper.mapviewpointer(
latitude: locData.latitude,
longitude: locData.longitude,
);
return staticMapUrl;
}
final mapview = _getUserLocation();
class NearbyScreen extends StatelessWidget {
#override
//LocationHelper.mapviewpointer(latitude: )
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Container(height:170, width: double.infinity,
child:Image.network(mapview.toString())
),
Text("hello"),
],
);
}
}
Does it have something to do with the fact that I am returning a Future<String> instead of just a string in my _getUserlocation function? How could I fix this?
Use the following settings.gradle:
include ':app'
def flutterProjectRoot = rootProject.projectDir.parentFile.toPath()
def plugins = new Properties()
def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins')
if (pluginsFile.exists()) {
pluginsFile.withReader('UTF-8') { reader -> plugins.load(reader) }
}
plugins.each { name, path ->
def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile()
include ":$name"
project(":$name").projectDir = pluginDirectory
}
This will create a .flutter-plugin file which will have the plugin and its path.
I had the same issue and following #Peter Haddad answer, I copy and replaced the code in settings.gradle (all of it) and I had errors resolving symbol for properties and file.
TO FIX IT: go to Tools -> Flutter -> Open for editing in Android Studio
In the Android Studio window go to File -> Invalidate Cache and Restart
This seemed to fix it for me.
add in your flutter app -> android -> settings.gradle
def flutterProjectRoot = rootProject.projectDir.parentFile.toPath()
def plugins = new Properties()
def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins')
if (pluginsFile.exists()) {
pluginsFile.withReader('UTF-8') { reader -> plugins.load(reader) }
}
plugins.each { name, path ->
def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile()
include ":$name"
project(":$name").projectDir = pluginDirectory
}
as seen here
more info about the issue here
Delete ProjectName/Build folder it has resolved issue for me.
Fix for users having facebook flipper installed
I would have added this as a comment, but let me post it as an answer to have proper code formatting.
If you have facebook's flipper installed, with the relative flutter_flipperkit plugin, then your settings.gradle should be already modified.
To use the fix suggested by #Peter Haddad & #Paulo Belo, you will need to keep flipper's plugin loading and add the other condition:
plugins.each { name, path ->
def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile()
if (name == 'flutter_flipperkit') {
// flipper loading
include ':flipper-no-op'
project(':flipper-no-op').projectDir = new File(pluginDirectory, 'flipper-no-op')
}
else {
// location_web not found fix
include ":$name"
project(":$name").projectDir = pluginDirectory
}
}
Hope this helps somebody.

Flutter Square Plugin crashes in release only

Flutter Square plugin crashes only in release when I use invalid card or press back.
But when I use flutter run --release & hook up my mobile. the crashes don't occur & the app works perfectly!
here's the code we used
void _pay() async {
await InAppPayments.setSquareApplicationId(sqAppId);
try {
await InAppPayments.startCardEntryFlowWithBuyerVerification(
money: Money((money) => money
..amount = 0
..currencyCode = 'USD'),
collectPostalCode: true,
contact: Contact((ContactBuilder contact) {
return contact.givenName = username;
}),
buyerAction: "Store",
squareLocationId: sqLocationId,
onBuyerVerificationSuccess: (BuyerVerificationDetails result) {
addCard(result.nonce, result.card.postalCode);
},
onBuyerVerificationFailure: (err) {
return showErrorDialog(context, err.toString());
},
onCardEntryCancel: () {});
} on Exception catch (e) {
print(e);
}
}
What is the difference between flutter build & flutter run --release ?
Could I use the APK out from flutter run & upload it to google play ?
In the release version you have to add the PERMISSIONS explicitly.
Try adding android.permission.INTERNET to the Manifest file.
Add
<uses-permission android:name="android.permission.INTERNET"/>
to the AndroidManifest.xml located in android/app/src/main.
For your question about uploading a debuggable apk, Google Play-Upload will reject your file.
Refer to this link for the differences between release and debug.