flutter url_launcher plugin issue for android release variant - android

When trying to run a url on browser with url_launcher plugin, I am getting this error on the release build on android. IOS and the android debug variant works fine.
E/flutter: [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: MissingPluginException(No implementation found for method canLaunch on channel plugins.flutter.io/url_launcher)
#0 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:157)
<asynchronous suspension>
#1 canLaunch (package:url_launcher/url_launcher.dart:124)
<asynchronous suspension>
#2 _HomeWidgetState.launchURL (package:pool_inspection/src/pages/home/home.dart:323)
<asynchronous suspension>
Here's my code
DialogButton(
color: Color(0xFF0B9CDA),
child: Text(
"Login Now",
style: TextStyle(
color: Colors.white, fontSize: 18),
),
onPressed: () {
setState(() {
launchURL();
});
},
)
Method for url launch
Future<void> launchURL() async {
const url = 'https://sometesturl.com';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
url_launcher version
url_launcher: ^5.7.10
Whats the issue I am unable to trace. I have already tried flutter clean,flutter pub get, Invalidate Cache/Restart as suggested by other answers.

Related

Permissions in flutter background_fetch headless task

I've got an Android app written in Dart using the Flutter framework. When it's first opened up, it requests permission to access location in the background. When the user opens the app using the launcher icon, this all works fine.
I use the background_fetch package to configure a headless task that runs on boot. This works, but it appears the context this runs in doesn't have the same permissions as the app. I check the permissions like this:
status = await Permission.location.status;
locationGranted = status.isGranted;
status = await Permission.locationAlways.status;
locationAlwaysGranted = status.isGranted;
if (locationAlwaysGranted) {
...
}
If I run this code from the app's main() then the body of the if statement is executed; when it runs from the headless task after the phone restarts, the body of the if block is not executed.
Is there a way to get the headless task to have the same permissions as the app? Or is there a better way to restart background location tracking after a phone restart?
The background-fetch task is configured like this:
BackgroundFetch.registerHeadlessTask(headlessTask);
BackgroundFetch.configure(BackgroundFetchConfig(
minimumFetchInterval: 15,
stopOnTerminate: false,
enableHeadless: true,
startOnBoot: true,
requiresBatteryNotLow: false,
requiresStorageNotLow: false,
requiresCharging: false,
requiresDeviceIdle: false,
requiredNetworkType: NetworkType.NONE
), (String taskId) {
...
BackgroundFetch.finish(taskId);
});
BackgroundFetch.scheduleTask(TaskConfig(
delay: 0,
periodic: false,
startOnBoot: true,
taskId: "gfz_on_boot",
enableHeadless: true
));
Edited to add this is the stack trace that appears in the flutter logs:
E/flutter ( 6464): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: PlatformException(PermissionHandler.PermissionManager, Unable to detect current Android Activity., null, null)
E/flutter ( 6464): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:607:7)
E/flutter ( 6464): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:167:18)
E/flutter ( 6464): <asynchronous suspension>
E/flutter ( 6464): #2 MethodChannelPermissionHandler.requestPermissions (package:permission_handler_platform_interface/src/method_channel/method_channel_permission_handler.dart:71:9)
E/flutter ( 6464): <asynchronous suspension>
E/flutter ( 6464): #3 GFZModel.updatePermissions (package:gfz_app/model.dart:349:24)
E/flutter ( 6464): <asynchronous suspension>
This makes sense at one level - there is no current activity in the background task - but how can we use permissions in background tasks?

Firebase fails to initialise on release build, Flutter

Am new to flutter and was trying around Firebase, but the app doesn't initialize Firebase on release
it throws an error, yet it works wen you just run the app. Am using android studio
** E/flutter (12950): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: MissingPluginException(No implementation found
for method Firebase#initializeC ore on channel
plugins.flutter.io/firebase_core)
E/flutter (12950): #0 MethodChannel._invokeMethod
(package:flutter/src/services/platform_channel.dart:156) E/flutter
(12950): E/flutter (12950): #1
MethodChannel.invokeListMethod
(package:flutter/src/services/platform_channel.dart:344) E/flutter
(12950):
E/flutter (12950): #2 MethodChannelFirebase._initializeCore
(package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:30)
E/flutter (12950):
E/flutter (12950): #3 MethodChannelFirebase.initializeApp
(package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:75)
E/flutter (12950):
E/flutter (12950): #4 Firebase.initializeApp
(package:firebase_core/src/firebase.dart:44) E/flutter (12950):
E/flutter (12950): #5 main
(package:ug_campus_papers_example/main.dart:13) E/flutter (12950):
E/flutter (12950):
**
Line 13 is the await Firebase.initializeApp();
My Main file is
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'App1 Test',
home: StreamBuilder(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (BuildContext context, AsyncSnapshot<User> snapshot) {
if (snapshot.hasData) {
User user = FirebaseAuth.instance.currentUser;
return Make1(user: user,);
} else
return SignInScreen();
},
),
);
}
}
The pubspec.yaml file is as below
name: ug_camp_example
description: My Flutter app 1.
version: 3.0.1+3
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
firebase_core: "^0.7.0"
firebase_storage: "^7.0.0"
firebase_auth: "^0.20.1"
cloud_firestore: "^0.16.0+1"
ug_camp:
path: ../
cupertino_icons: ^1.0.2
google_fonts:
provider:
file_picker: ^1.1.1
flutter_plugin_pdf_viewer:
sqflite:
path:
flutterwave:
flutter_launcher_icons: ^0.7.4
dev_dependencies:
flutter_test:
sdk: flutter
flutter_icons:
image_path: "assets/images/apptest1.png"
android: true
ios: true
flutter:
uses-material-design: true
Please try the following:
Update your firebase packages to the latest versions. You're very outdated.
Ensure you've added your google-services.json to the project.
You mentioned you are using Android Studio, although are you running on Android or iOS? I can provide more instructions depending on the platform.

How to open PDF file from internal storage in flutter

Used Plugin for the code
native_pdf_view: ^4.0.1
Sample code where is am getting error, I am able to use pdf file from assets but not able to load pdf from local storage
return Container(
child: PdfView(
controller:
// sample,
PdfController(
document: PdfDocument.openFile(widget.path),
),
onDocumentLoaded: (document) {
setState(() {
isLoaded = true;
});
},
pageLoader: Center(child: CircularProgressIndicator()),
),
);
error, it says the file was not found but this file path was extracted from the existing file
D/PDF_RENDER( 585): OpenFileDocument. File: /storage/emulated/0/Doc_Holder/c4611_sample_explain.pdf
D/PDF_RENDER( 585): OpenAssetDocument. Created file: /data/user/0/com.example.doc_holder/cache/992d7c88890d40268ae7ac4103bf96ba.pdf
D/PDF_RENDER( 585): OpenFileDocument. File: /data/user/0/com.example.doc_holder/cache/992d7c88890d40268ae7ac4103bf96ba.pdf
D/PDF_RENDER( 585): OpenFileDocument. File: /storage/emulated/0/Doc_Holder/c4611_sample_explain.pdf
════════ Exception caught by widgets library ═══════════════════════════════════
The following _CastError was thrown building PdfView(dirty, state: _PdfViewState#6990d):
Null check operator used on a null value
The relevant error-causing widget was
PdfView
lib/const/pdf.dart:23
When the exception was thrown, this was the stack
#0 _PdfViewState._buildLoaded
package:native_pdf_view/src/native_pdf_view.dart:172
#1 _PdfViewState.build
package:native_pdf_view/src/native_pdf_view.dart:205
#2 StatefulElement.build
package:flutter/…/widgets/framework.dart:4683
#3 ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:4566
#4 StatefulElement.performRebuild
package:flutter/…/widgets/framework.dart:4738
...
Please try any of them
pdf: ^3.3.0,
flutter_full_pdf_viewer: ^1.0.6,
syncfusion_flutter_pdfviewer: ^19.1.58-beta,
syncfusion_flutter_pdfviewer_platform_interface: ^19.1.58-beta

Image Not Loading in flutter android

I tried everything but nothing seems to work. According to me, the path of the image is correct. (though I have attached an image for reference). This is the error I am getting -
════════ Exception caught by image resource service ════════════════════════════
The following assertion was thrown resolving an image codec:
Unable to load asset: start.png
When the exception was thrown, this was the stack
#0 PlatformAssetBundle.load
package:flutter/…/services/asset_bundle.dart:225
<asynchronous suspension>
#1 AssetBundleImageProvider._loadAsync
package:flutter/…/painting/image_provider.dart:668
#2 AssetBundleImageProvider.load
package:flutter/…/painting/image_provider.dart:651
#3 ImageProvider.resolveStreamForKey.<anonymous closure>
package:flutter/…/painting/image_provider.dart:504
...
Image provider: AssetImage(bundle: null, name: "start.png")
Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#2bd13(), name: "start.png", scale: 1.0)
════════════════════════════════════════════════════════════════════════════════
this is **pubspec.yaml*-
name: foodfast
description: A new Flutter project.
publish_to: 'none'
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
splashscreen: ^1.3.5
cupertino_icons: ^1.0.0
firebase_auth: ^0.20.0+1
cloud_firestore: ^0.16.0
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- assets/start.png
sign_in.dart
import 'package:flutter/material.dart';
class SignIn extends StatefulWidget {
#override
_SignInState createState() => _SignInState();
}
class _SignInState extends State<SignIn> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
title: new Text('sign in'),
),
backgroundColor: Colors.white,
body: Center(
child: ListView(
children: <Widget>[
Image(image: AssetImage('start.png'), fit: BoxFit.cover),
new Text('text below image')
],
)),
);
}
}
You need to add your path of image first i.e. assets and then add image name
Image(image: AssetImage('assets/start.png'), fit: BoxFit.cover),
Provide the full path even if you have already given it in pubspec.yaml.
Hence, it should be 'assets/start.png'
Use full path like 'assets/start.png' in your image path.
Image(image: AssetImage('assets/start.png'), fit: BoxFit.cover),
Try changing the path from
AssetImage("/image/start.png")
to
AssetImage("./image/start.png")
(. means go to the highest folder level)
This worked for me!

Send platform message to Android method from background flutter isolate

I want to have a dart background service running forever (isolates) which will communicate with a server through websockets. And I have an API for Android which gather information to send to the server.
How can I invoke that Android methods which use callbacks and everything from the background isolate?
EDIT
So far in dart I created an Isolate to periodically invoke the poolSong method in background even if the user is using another app or has the screen turned off.
But that gives me the error below...on the github issues they say that I can't send a platform message from a different Isolate unless it's the main. But if I do it from the main isolate, when the user exit the app that isolate will terminate too.
MainDart
class _MyHomePageState extends State<MyHomePage> {
final GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();
static const platform = const MethodChannel('mainService');
static _poolSong(SendPort sendPort) async {
const oneSec = const Duration(seconds:1);
new Timer.periodic(oneSec, (Timer t) => platform.invokeMethod('poolSong'));
}
#override
void initState() {
super.initState();
ReceivePort receivePort = ReceivePort();
Isolate.spawn(_poolSong, receivePort.sendPort);
}
·
·
·
MainActivityJava
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
(call, result) -> {
if (call.method.equals("startService"))
startService();
if (call.method.equals("poolSong"))
poolSong();
}
);
}
ERROR
E/flutter (25412): [ERROR:flutter/runtime/dart_isolate.cc(717)] Isolate (765499726) 'main.dart:_poolSong()' exited with an error
E/flutter (25412): [ERROR:flutter/shell/common/shell.cc(186)] Dart Error: Unhandled exception:
E/flutter (25412): error: native function 'Window_sendPlatformMessage' (4 arguments) cannot be found
E/flutter (25412): #0 Window.sendPlatformMessage (dart:ui/window.dart:811:9)
E/flutter (25412): #1 BinaryMessages._sendPlatformMessage (package:flutter/src/services/platform_messages.dart:39:15)
E/flutter (25412): #2 BinaryMessages.send (package:flutter/src/services/platform_messages.dart:87:12)
E/flutter (25412): #3 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:286:49)
E/flutter (25412): <asynchronous suspension>
E/flutter (25412): #4 _MyHomePageState._poolSong.<anonymous closure> (package:musictie/main.dart:37:54)
E/flutter (25412): #5 _Timer._runTimers (dart:isolate/runtime/libtimer_impl.dart:382:19)
E/flutter (25412): #6 _Timer._handleMessage (dart:isolate/runtime/libtimer_impl.dart:416:5)
E/flutter (25412): #7 _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)
This error happens when trying to run dart code when the app is in the garbage (app closed), Until now the best way for dealing with background service is to do what you need in native code, and dont try to run anything from dart when app closed.
Since Flutter 3.7 plugins and platform channels can be used from any isolate, not only from the root one.
References:
https://medium.com/flutter/introducing-background-isolate-channels-7a299609cad8
https://github.com/flutter/flutter/issues/13937

Categories

Resources