The code for the app in which initializing firebase:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
void initState() {
// TODO: implement initState
super.initState();
FirebaseMessaging.instance.getInitialMessage();
///foreground notification
FirebaseMessaging.onMessage.listen((message) {
if (message.notification != null) {
print(message.notification!.title);
print(message.notification!.body);
}
});
///background & opened notification
///tapped on notification
FirebaseMessaging.onMessageOpenedApp.listen((message) {
final routeFromMessage = message.data['route'];
Navigator.of(context).pushNamed(routeFromMessage);
});
}
Now if the code worked correctly, it should have navigated me to the respective routed page and printed the notification title and body in the console.
But instead I am getting errors like this:
D/FLTFireMsgReceiver( 9928): broadcast received for message
W/FLTFireMsgService( 9928): A background message could not be handled in Dart as no onBackgroundMessage handler has been registered.
W/FirebaseMessaging( 9928): Missing Default Notification Channel metadata in AndroidManifest. Default value will be used.
E/flutter ( 9928): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Navigator operation requested with a context that does not include a Navigator.
E/flutter ( 9928): The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.
E/flutter ( 9928): #0 Navigator.of.<anonymous closure>
package:flutter/…/widgets/navigator.dart:2553
E/flutter ( 9928): #1 Navigator.of
package:flutter/…/widgets/navigator.dart:2560
E/flutter ( 9928): #2 _MyAppState.initState.<anonymous closure>
package:note_reminder/main.dart:42
E/flutter ( 9928): #3 _rootRunUnary (dart:async/zone.dart:1434:47)
E/flutter ( 9928): #4 _CustomZone.runUnary (dart:async/zone.dart:1335:19)
E/flutter ( 9928): #5 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1244:7)
E/flutter ( 9928): #6 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)
E/flutter ( 9928): #7 _DelayedData.perform (dart:async/stream_impl.dart:591:14)
E/flutter ( 9928): #8 _StreamImplEvents.handleNext (dart:async/stream_impl.dart:706:11)
E/flutter ( 9928): #9 _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:663:7)
E/flutter ( 9928): #10 _rootRun (dart:async/zone.dart:1418:47)
E/flutter ( 9928): #11 _CustomZone.run (dart:async/zone.dart:1328:19)
E/flutter ( 9928): #12 _CustomZone.runGuarded (dart:async/zone.dart:1236:7)
E/flutter ( 9928): #13 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1276:23)
E/flutter ( 9928): #14 _rootRun (dart:async/zone.dart:1426:13)
E/flutter ( 9928): #15 _CustomZone.run (dart:async/zone.dart:1328:19)
E/flutter ( 9928): #16 _CustomZone.runGuarded (dart:async/zone.dart:1236:7)
E/flutter ( 9928): #17 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1276:23)
E/flutter ( 9928): #18 _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
E/flutter ( 9928): #19 _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)
E/flutter ( 9928):
I/OpenGLRenderer( 9928): Davey! duration=567777ms; Flags=1, FrameTimelineVsyncId=76328, IntendedVsync=19427849009190, Vsync=19427849009190, InputEventId=0, HandleInputStart=19427850193500, AnimationStart=19427850214100, PerformTraversalsStart=19427851010200, DrawStart=19427851815400, FrameDeadline=19427899009188, FrameInterval=19427850132400, FrameStartTime=16666666, SyncQueued=19427852843800, SyncStart=19427853556300, IssueDrawCommandsStart=19427855478900, SwapBuffers=19427864095600, FrameCompleted=19995626844200, DequeueBufferDuration=7109800, QueueBufferDuration=670800, GpuCompleted=19995626844200, SwapBuffersCompleted=19427873795500, DisplayPresentTime=25614609433559128,
Also note that I am trying to route to a screen that I am using with a custom navbar.
Code of routes:
home: OnBoardingPage(),
routes: {
'done': (context) => DonePage(),
'create': (context) => CreatePage(),
'history': (context) => HistoryPage(),
Code of my Home Page:
class _HomePageState extends State<HomePage> {
int _currentIndex = 0;
final screens = [DonePage(), CreatePage(), HistoryPage()];
#override
Widget build(BuildContext context) => SafeArea(
child: Scaffold(
body: screens[_currentIndex],
)
We have education app created with Flutter, this app very same to Udemy app features.
in this app the course may contain videos lectures of PDF files
all things working well except PDF downloading
The situation is:
when user click on PDF file name in lectures list, will open download page, it's contain only one button
when user click download button, download process start and download notification appear in notifications area
after few seconds notification show file link and failed message
I'm not sure what the problem here
Note that: the app was published on play & app store, and the PDF file download is fail in test mode and published versions.
the run log file for download process:
E/flutter (27102): #5 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1244:7)
E/flutter (27102): #6 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)
E/flutter (27102): #7 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)
E/flutter (27102): #8 _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:733:19)
E/flutter (27102): #9 _StreamController._add (dart:async/stream_controller.dart:607:7)
E/flutter (27102): #10 _StreamController.add (dart:async/stream_controller.dart:554:5)
E/flutter (27102): #11 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
E/flutter (27102):
D/DownloadWorker(27102): Content-Type = application/pdf
D/DownloadWorker(27102): Content-Length = 1165606
D/DownloadWorker(27102): Charset = null
D/DownloadWorker(27102): Content-Disposition = null
D/DownloadWorker(27102): fileName = 7339d9826c027c3facdf76b943e452eb.pdf
W/System.err(27102): java.io.IOException: Permission denied
W/System.err(27102): at java.io.UnixFileSystem.createFileExclusively0(Native Method)
W/System.err(27102): at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:317)
W/System.err(27102): at java.io.File.createNewFile(File.java:1008)
W/System.err(27102): at vn.hunghd.flutterdownloader.DownloadWorker.createDownloadFileWithDirectFilePath(DownloadWorker.java:490)
W/System.err(27102): at vn.hunghd.flutterdownloader.DownloadWorker.downloadFile(DownloadWorker.java:393)
W/System.err(27102): at vn.hunghd.flutterdownloader.DownloadWorker.doWork(DownloadWorker.java:232)
W/System.err(27102): at androidx.work.Worker$1.run(Worker.java:86)
W/System.err(27102): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
W/System.err(27102): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
W/System.err(27102): at java.lang.Thread.run(Thread.java:919)
E/DownloadWorker(27102): Create a file using java.io API failed
D/DownloadWorker(27102): Update too frequently!!!!, but it is the final update, we should sleep a second to ensure the update call can be processed
E/flutter (27102): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: setState() called after dispose(): _MyCourseDownloadScreenState#6a6b6(lifecycle state: defunct, not mounted)
E/flutter (27102): This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback.
E/flutter (27102): The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree.
E/flutter (27102): This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose().
E/flutter (27102): #0 State.setState.<anonymous closure> (package:flutter/src/widgets/framework.dart:1052:9)
E/flutter (27102): #1 State.setState (package:flutter/src/widgets/framework.dart:1087:6)
E/flutter (27102): #2 _MyCourseDownloadScreenState.initState.<anonymous closure> (package:connect/screens/my_course_download_screen.dart:43:7)
E/flutter (27102): #3 _rootRunUnary (dart:async/zone.dart:1444:13)
E/flutter (27102): #4 _CustomZone.runUnary (dart:async/zone.dart:1335:19)
E/flutter (27102): #5 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1244:7)
E/flutter (27102): #6 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)
E/flutter (27102): #7 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)
E/flutter (27102): #8 _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:733:19)
E/flutter (27102): #9 _StreamController._add (dart:async/stream_controller.dart:607:7)
E/flutter (27102): #10 _StreamController.add (dart:async/stream_controller.dart:554:5)
E/flutter (27102): #11 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
E/flutter (27102):
D/Surface (27102): Surface::disconnect(this=0x701217d000,api=1)
D/View (27102): [Warning] assignParent to null: this = android.widget.FrameLayout{f9df83 V.E...... ......ID 0,0-376,125}
I/InputTransport(27102): Destroy ARC handle: 0x708af9a7c0
D/DownloadWorker(27102): Update notification: {notificationId: 3, title: https://connect-elearning.com/newVersion/uploads/lesson_files/7339d9826c027c3facdf76b943e452eb.pdf, status: 4, progress: -1}
W/System.err(27102): java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.io.File.getPath()' on a null object reference
W/System.err(27102): at vn.hunghd.flutterdownloader.DownloadWorker.downloadFile(DownloadWorker.java:394)
W/System.err(27102): at vn.hunghd.flutterdownloader.DownloadWorker.doWork(DownloadWorker.java:232)
W/System.err(27102): at androidx.work.Worker$1.run(Worker.java:86)
W/System.err(27102): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
W/System.err(27102): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
W/System.err(27102): at java.lang.Thread.run(Thread.java:919)
I/WM-WorkerWrapper(27102): Worker result FAILURE for Work [ id=99a29ba5-9003-4ef4-9f19-9fda892a3c5b, tags={ flutter_download_task, vn.hunghd.flutterdownloader.DownloadWorker } ]
download page code:
import 'dart:io';
import 'dart:isolate';
import 'dart:ui';
import 'package:connect/models/common_functions.dart';
import 'package:connect/widgets/app_bar_two.dart';
import 'package:file_utils/file_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import '../constants.dart';
class MyCourseDownloadScreen extends StatefulWidget {
static const routeName = '/my-download-screen';
#override
_MyCourseDownloadScreenState createState() => _MyCourseDownloadScreenState();
}
class _MyCourseDownloadScreenState extends State<MyCourseDownloadScreen> {
int progress = 0;
ReceivePort _receivePort = ReceivePort();
static downloadingCallback(id, status, progress) {
///Looking up for a send port
SendPort sendPort = IsolateNameServer.lookupPortByName("downloading");
///ssending the data
sendPort.send([id, status, progress]);
}
#override
void initState() {
super.initState();
IsolateNameServer.registerPortWithName(_receivePort.sendPort, "downloading");
///Listening for the data is coming other isolates
_receivePort.listen((message) {
progress = message[2];
setState(() {
progress = message[2];
});
print(progress);
});
FlutterDownloader.registerCallback(downloadingCallback);
}
#override
Widget build(BuildContext context) {
final selectedUrl = ModalRoute.of(context).settings.arguments as String;
return Scaffold(
appBar: CustomAppBarTwo(),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
FlatButton(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text("Download File", style: TextStyle(fontSize: 18),),
),
color: Colors.redAccent,
textColor: Colors.white,
onPressed: () async {
final status = await Permission.storage.request();
String externalDir = "";
if (status.isGranted) {
if (Platform.isAndroid) {
externalDir = "/sdcard/download/";
} else {
externalDir = (await getApplicationDocumentsDirectory()).path;
}
try {
FileUtils.mkdir([externalDir]);
final id = await FlutterDownloader.enqueue(
url: selectedUrl,
savedDir: externalDir,
// fileName: "download1234.pdf",
showNotification: true,
openFileFromNotification: true,
);
CommonFunctions.showSuccessToast("Downloading");
} catch(e){
print(e.getMessage());
CommonFunctions.showSuccessToast("Download Error");
}
} else {
print("Permission denied");
}
},
)
],
),
),
);
}
}
So, I'm trying to have this sound from Flutter assets when I click the button. And I've tried many different packages by this moment and none of them seems to work for me.
I'm constantly getting this:
D/ViewRootImpl( 8796): enqueueInputEventMotionEvent { action=ACTION_DOWN, actionButton=0, id[0]=0, x[0]=582.0, y[0]=1570.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, classification=NONE, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=48512196, downTime=48512196, deviceId=-1, source=0x1002, displayId=0 }
D/ViewRootImpl[MainActivity]( 8796): processMotionEvent MotionEvent { action=ACTION_DOWN, actionButton=0, id[0]=0, x[0]=582.0, y[0]=1570.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, classification=NONE, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=48512196, downTime=48512196, deviceId=-1, source=0x1002, displayId=0 }
D/ViewRootImpl[MainActivity]( 8796): dispatchPointerEvent handled=true, event=MotionEvent { action=ACTION_DOWN, actionButton=0, id[0]=0, x[0]=582.0, y[0]=1570.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, classification=NONE, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=48512196, downTime=48512196, deviceId=-1, source=0x1002, displayId=0 }
W/Choreographer( 8796): Frame time is 0.144734 ms in the future! Check that graphics HAL is generating vsync timestamps using the correct timebase.
D/ViewRootImpl[MainActivity]( 8796): processMotionEvent MotionEvent { action=ACTION_UP, actionButton=0, id[0]=0, x[0]=582.0, y[0]=1570.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, classification=NONE, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=48512312, downTime=48512196, deviceId=-1, source=0x1002, displayId=0 }
D/ViewRootImpl[MainActivity]( 8796): dispatchPointerEvent handled=true, event=MotionEvent { action=ACTION_UP, actionButton=0, id[0]=0, x[0]=582.0, y[0]=1570.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, classification=NONE, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=48512312, downTime=48512196, deviceId=-1, source=0x1002, displayId=0 }
I/ExoPlayerImpl( 8796): Init e31da6b [ExoPlayerLib/2.13.1] [RMX2025CN, RMX2025, realme, 30]
D/AudioManager( 8796): getStreamVolume packageName=com.example.dicee_v2_red, index=14, streamType=3
E/ExoPlayerImplInternal( 8796): Playback error
E/ExoPlayerImplInternal( 8796): com.google.android.exoplayer2.ExoPlaybackException: Source error
E/ExoPlayerImplInternal( 8796): at com.google.android.exoplayer2.ExoPlayerImplInternal.handleMessage(ExoPlayerImplInternal.java:579)
E/ExoPlayerImplInternal( 8796): at android.os.Handler.dispatchMessage(Handler.java:102)
E/ExoPlayerImplInternal( 8796): at android.os.Looper.loop(Looper.java:260)
E/ExoPlayerImplInternal( 8796): at android.os.HandlerThread.run(HandlerThread.java:67)
E/ExoPlayerImplInternal( 8796): Caused by: com.google.android.exoplayer2.source.UnrecognizedInputFormatException: None of the available extractors (Mp3Extractor, FlvExtractor, FlacExtractor, WavExtractor, FragmentedMp4Extractor, Mp4Extractor, AmrExtractor, PsExtractor, OggExtractor, TsExtractor, MatroskaExtractor, AdtsExtractor, Ac3Extractor, Ac4Extractor, JpegExtractor) could read the stream.
E/ExoPlayerImplInternal( 8796): at com.google.android.exoplayer2.source.BundledExtractorsAdapter.init(BundledExtractorsAdapter.java:92)
E/ExoPlayerImplInternal( 8796): at com.google.android.exoplayer2.source.ProgressiveMediaPeriod$ExtractingLoadable.load(ProgressiveMediaPeriod.java:1026)
E/ExoPlayerImplInternal( 8796): at com.google.android.exoplayer2.upstream.Loader$LoadTask.run(Loader.java:415)
E/ExoPlayerImplInternal( 8796): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
E/ExoPlayerImplInternal( 8796): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
E/ExoPlayerImplInternal( 8796): at java.lang.Thread.run(Thread.java:923)
E/AudioPlayer( 8796): TYPE_SOURCE: None of the available extractors (Mp3Extractor, FlvExtractor, FlacExtractor, WavExtractor, FragmentedMp4Extractor, Mp4Extractor, AmrExtractor, PsExtractor, OggExtractor, TsExtractor, MatroskaExtractor, AdtsExtractor, Ac3Extractor, Ac4Extractor, JpegExtractor) could read the stream.
E/flutter ( 8796): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: (0) Source error
E/flutter ( 8796): #0 AudioPlayer._load (package:just_audio/just_audio.dart:716:9)
E/flutter ( 8796): <asynchronous suspension>
E/flutter ( 8796): #1 AudioPlayer._setPlatformActive.setPlatform (package:just_audio/just_audio.dart:1096:28)
E/flutter ( 8796): <asynchronous suspension>
E/flutter ( 8796):
I/ExoPlayerImpl( 8796): Release e31da6b [ExoPlayerLib/2.13.1] [RMX2025CN, RMX2025, realme, 30] [goog.exo.core]
But when I load my app in Web, it works perfectly fine. Why?
My code:
import 'package:flutter/material.dart';
import 'dart:math';
import 'package:flutter/services.dart';
import 'package:just_audio/just_audio.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
.then((_) {
runApp(
MaterialApp(
home: Scaffold(
backgroundColor: Colors.red,
appBar: AppBar(
title: Text('Dicee'),
backgroundColor: Colors.blue.shade300,
),
body: NewDice(),
),
),
);
});
}
class NewDice extends StatefulWidget {
#override
_NewDiceState createState() => _NewDiceState();
}
class _NewDiceState extends State<NewDice> {
late AudioPlayer player;
#override
void initState() {
super.initState();
player = AudioPlayer();
}
#override
void dispose() {
player.dispose();
super.dispose();
}
int leftDiceNumber = 1;
int rightDiceNumber = 1;
#override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Image.asset('assets/dice$leftDiceNumber.png'),
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Image.asset('assets/dice$rightDiceNumber.png'),
),
),
],
),
ElevatedButton(
onPressed: () async {
await player.setAsset('audio/roll.mp3');
player.play();
setState(() {
rightDiceNumber = Random().nextInt(6) + 1;
leftDiceNumber = Random().nextInt(6) + 1;
});
},
style: ElevatedButton.styleFrom(
primary: Colors.blue.shade300,
),
child: Text('Roll the dice!',
style: TextStyle(
fontSize: 18,
)),
),
],
);
}
}
Please help :)
I have also tried flutter_audio_player 0.1.2 and many other packages... none seems to work...
tried audiofileplayer 2.0.1, another bug now...
I/AudiofileplayerPlugin(11305): onMethodCall: method = load
I/AudiofileplayerPlugin(11305): onMethodCall: method = play
E/MethodChannel#audiofileplayer(11305): Failed to handle method call
E/MethodChannel#audiofileplayer(11305): java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.flutter.plugins.audiofileplayer.ManagedMediaPlayer.play(boolean, int)' on a null object reference
E/MethodChannel#audiofileplayer(11305): at com.google.flutter.plugins.audiofileplayer.AudiofileplayerPlugin.onMethodCall(AudiofileplayerPlugin.java:256)
E/MethodChannel#audiofileplayer(11305): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:233)
E/MethodChannel#audiofileplayer(11305): at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:85)
E/MethodChannel#audiofileplayer(11305): at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:818)
E/MethodChannel#audiofileplayer(11305): at android.os.MessageQueue.nativePollOnce(Native Method)
E/MethodChannel#audiofileplayer(11305): at android.os.MessageQueue.next(MessageQueue.java:335)
E/MethodChannel#audiofileplayer(11305): at android.os.Looper.loop(Looper.java:183)
E/MethodChannel#audiofileplayer(11305): at android.app.ActivityThread.main(ActivityThread.java:7656)
E/MethodChannel#audiofileplayer(11305): at java.lang.reflect.Method.invoke(Native Method)
E/MethodChannel#audiofileplayer(11305): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
E/MethodChannel#audiofileplayer(11305): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
E/DartMessenger(11305): Uncaught exception in binary message listener
E/DartMessenger(11305): java.lang.IllegalStateException: Reply already submitted
E/DartMessenger(11305): at io.flutter.embedding.engine.dart.DartMessenger$Reply.reply(DartMessenger.java:155)
E/DartMessenger(11305): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:253)
E/DartMessenger(11305): at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:85)
E/DartMessenger(11305): at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:818)
E/DartMessenger(11305): at android.os.MessageQueue.nativePollOnce(Native Method)
E/DartMessenger(11305): at android.os.MessageQueue.next(MessageQueue.java:335)
E/DartMessenger(11305): at android.os.Looper.loop(Looper.java:183)
E/DartMessenger(11305): at android.app.ActivityThread.main(ActivityThread.java:7656)
E/DartMessenger(11305): at java.lang.reflect.Method.invoke(Native Method)
E/DartMessenger(11305): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
E/DartMessenger(11305): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
E/flutter (11305): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: PlatformException(AudioPluginError, Could not create ManagedMediaPlayer:flutter_assets/assets/audio/roll2.wav, null, null)
E/flutter (11305): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:597:7)
E/flutter (11305): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:158:18)
E/flutter (11305): <asynchronous suspension>
E/flutter (11305): #2 Audio._sendMethodCall (package:audiofileplayer/audiofileplayer.dart:751:7)
E/flutter (11305): <asynchronous suspension>
E/flutter (11305): #3 Audio._load (package:audiofileplayer/audiofileplayer.dart:433:7)
E/flutter (11305): <asynchronous suspension>
E/flutter (11305):
E/flutter (11305): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: PlatformException(AudioPluginError, Called play on an unloaded player: 8dbbdf54-e262-4c2a-af1c-e6cbff1ac399, null, null)
E/flutter (11305): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:597:7)
E/flutter (11305): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:158:18)
E/flutter (11305): <asynchronous suspension>
E/flutter (11305): #2 Audio._sendMethodCall (package:audiofileplayer/audiofileplayer.dart:751:7)
E/flutter (11305): <asynchronous suspension>
E/flutter (11305): #3 Audio._playNative (package:audiofileplayer/audiofileplayer.dart:661:7)
E/flutter (11305): <asynchronous suspension>
E/flutter (11305): #4 Audio._playHelper (package:audiofileplayer/audiofileplayer.dart:556:5)
E/flutter (11305): <asynchronous suspension>
E/flutter (11305): #5 Audio.play (package:audiofileplayer/audiofileplayer.dart:517:5)
E/flutter (11305): <asynchronous suspension>
E/flutter (11305):
I had this issue and it was due to a bad MP3 file (that apparently Chrome knows how to play but ExoPlayer does not). I verified this by swapping in a known good MP3: flutter.github.io/samples/game_template/assets/sfx/dsht1.mp3 .
Try replacing your file with that and see if it works.
just_audio package has some issues with some emulators. You can create another emulator and probably it will work.
I am trying to navigate to a different screen using Get when a user taps on the notification triggered from the onMessage function while the app is on foreground. So far I have not been able to do that.
Here's what I have done so far:
void initState(){
super.initState();
var initializationSettingsAndroid = AndroidInitializationSettings('#drawable/splash');
var initializationSettings = InitializationSettings(android:initializationSettingsAndroid);
flutterLocalNotificationsPlugin.initialize(initializationSettings);
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
RemoteNotification notification = message.notification;
AndroidNotification android = message.notification?.android;
if (notification != null && android != null) {
flutterLocalNotificationsPlugin.show(
notification.hashCode,
notification.title,
notification.body,
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
channel.description,
icon: '#drawable/splash',
playSound: true
),
));
Get.to(OrdersScreen());
}
});
}
I get the notification but when I tap, nothing happens. I also get the following exception in the logs.
E/flutter (17567): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)]
Unhandled Exception: You are trying to use contextless navigation
without E/flutter (17567): a GetMaterialApp or Get.key.
E/flutter (17567): If you are testing your app, you can use:
E/flutter (17567): [Get.testMode = true], or if you are running
your app on E/flutter (17567): a physical device or emulator,
you must exchange your [MaterialApp] E/flutter (17567): for a
[GetMaterialApp]. E/flutter (17567): E/flutter (17567): #0
GetNavigation.global package:get/…/src/extension_navigation.dart:1052
E/flutter (17567): #1 GetNavigation.to
package:get/…/src/extension_navigation.dart:511 E/flutter (17567): #2
_MyAppState.initState. package:flutter_complete_guide/main.dart:146 E/flutter (17567): #3
_rootRunUnary (dart:async/zone.dart:1362:47) E/flutter (17567): #4 _CustomZone.runUnary (dart:async/zone.dart:1265:19) E/flutter (17567): #5 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1170:7) E/flutter (17567): #6 _BufferingStreamSubscription._sendData
(dart:async/stream_impl.dart:341:11) E/flutter (17567): #7
_DelayedData.perform (dart:async/stream_impl.dart:591:14) E/flutter (17567): #8 _StreamImplEvents.handleNext
(dart:async/stream_impl.dart:706:11) E/flutter (17567): #9
_PendingEvents.schedule. (dart:async/stream_impl.dart:663:7) E/flutter (17567): #10
_rootRun (dart:async/zone.dart:1346:47) E/flutter (17567): #11 _CustomZone.run (dart:async/zone.dart:1258:19) E/flutter (17567): #12 _CustomZone.runGuarded (dart:async/zone.dart:1162:7) E/flutter (17567): #13 _CustomZone.bindCallbackGuarded.
(dart:async/zone.dart:1202:23) E/flutter (17567): #14 _rootRun
(dart:async/zone.dart:1354:13) E/flutter (17567): #15
_CustomZone.run (dart:async/zone.dart:1258:19) E/flutter (17567): #16 _CustomZone.runGuarded (dart:async/zone.dart:1162:7) E/flutter (17567): #17 _CustomZone.bindCallbackGuarded.
(dart:async/zone.dart:1202:23) E/flutter (17567): #18
_microtaskLoop (dart:async/schedule_microtask.dart:40:21) E/flutter (17567): #19 _startMicrotaskLoop
(dart:async/schedule_microtask.dart:49:5) E/flutter (17567):
D/ViewRootImpl#874c66fMainActivity: stopped(false) old=false
I was able to do this using the navigatorkey.
Created the global key:
final GlobalKey<NavigatorState> navigatorKey = GlobalKey(debugLabel: "Main Navigator");
Initialized it in the MaterialApp:
MaterialApp(
navigatorKey: navigatorKey,
The used it inside onMessage function:
navigatorKey.currentState.push(
MaterialPageRoute(builder: (_) => OrdersScreen()));
to open a notification you have to use this
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
// print('A new onMessageOpenedApp event was published!');
Get.to(OrdersScreen());
});
I am writing a FLUTTER application and I am trying to upload an image on the Firebase storage. This is a simple test app I've created to reproduce the error.
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:path_provider/path_provider.dart';
import 'package:firebase_storage/firebase_storage.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
File image;
Future<File> getImageFileFromAssets(String path) async {
final byteData = await rootBundle.load('assets/$path');
final file = File('${(await getTemporaryDirectory()).path}/$path');
await file.writeAsBytes(byteData.buffer
.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
return file;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Test App'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
height: 300,
width: 450,
child: image == null ? null : Image.file(image),
),
RaisedButton(
child: Text('Submit'),
onPressed: () async {
final fileName = 'imageName';
final firebaseStorageRef =
FirebaseStorage.instance.ref().child('userFolder');
final uploadTask =
firebaseStorageRef.child(fileName).putFile(image);
await uploadTask.onComplete;
},
),
RaisedButton(
child: Text('Load immagine'),
onPressed: () async {
image = await getImageFileFromAssets('test.jpg');
setState(() {});
},
),
],
),
),
);
}
}
As you can see when I click on the Load Image button I take an image from the assets and I store it in a File object, and it works fine. Then when I want to upload that image on Firebase's storage using the Submit button I get this error:
E/MethodChannel#plugins.flutter.io/firebase_storage(19436): Failed to handle method call
E/MethodChannel#plugins.flutter.io/firebase_storage(19436): java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.example.test_project. Make sure to call FirebaseApp.initializeApp(Context) first.
E/MethodChannel#plugins.flutter.io/firebase_storage(19436): at com.google.firebase.FirebaseApp.getInstance(com.google.firebase:firebase-common##17.0.0:234)
E/MethodChannel#plugins.flutter.io/firebase_storage(19436): at com.google.firebase.storage.FirebaseStorage.getInstance(com.google.firebase:firebase-storage##17.0.0:86)
E/MethodChannel#plugins.flutter.io/firebase_storage(19436): at io.flutter.plugins.firebase.storage.FirebaseStoragePlugin.onMethodCall(FirebaseStoragePlugin.java:57)
E/MethodChannel#plugins.flutter.io/firebase_storage(19436): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:222)
E/MethodChannel#plugins.flutter.io/firebase_storage(19436): at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:96)
E/MethodChannel#plugins.flutter.io/firebase_storage(19436): at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:656)
E/MethodChannel#plugins.flutter.io/firebase_storage(19436): at android.os.MessageQueue.nativePollOnce(Native Method)
E/MethodChannel#plugins.flutter.io/firebase_storage(19436): at android.os.MessageQueue.next(MessageQueue.java:326)
E/MethodChannel#plugins.flutter.io/firebase_storage(19436): at android.os.Looper.loop(Looper.java:160)
E/MethodChannel#plugins.flutter.io/firebase_storage(19436): at android.app.ActivityThread.main(ActivityThread.java:6669)
E/MethodChannel#plugins.flutter.io/firebase_storage(19436): at java.lang.reflect.Method.invoke(Native Method)
E/MethodChannel#plugins.flutter.io/firebase_storage(19436): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
E/MethodChannel#plugins.flutter.io/firebase_storage(19436): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
E/flutter (19436): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: PlatformException(error, Default FirebaseApp is not initialized in this process com.example.test_project. Make sure to call FirebaseApp.initializeApp(Context) first., null)
E/flutter (19436): #0 StandardMethodCodec.decodeEnvelope
package:flutter/…/services/message_codecs.dart:569
E/flutter (19436): #1 MethodChannel.invokeMethod
package:flutter/…/services/platform_channel.dart:316
E/flutter (19436): <asynchronous suspension>
E/flutter (19436): #2 _StorageFileUploadTask._platformStart
package:firebase_storage/src/upload_task.dart:130
E/flutter (19436): #3 StorageUploadTask._start
package:firebase_storage/src/upload_task.dart:35
E/flutter (19436): <asynchronous suspension>
E/flutter (19436): #4 StorageReference.putFile
package:firebase_storage/src/storage_reference.dart:65
E/flutter (19436): #5 _MyHomePageState.build.<anonymous closure>
package:test_project/main.dart:60
E/flutter (19436): <asynchronous suspension>
E/flutter (19436): #6 _InkResponseState._handleTap
package:flutter/…/material/ink_well.dart:654
E/flutter (19436): #7 _InkResponseState.build.<anonymous closure>
package:flutter/…/material/ink_well.dart:729
E/flutter (19436): #8 GestureRecognizer.invokeCallback
package:flutter/…/gestures/recognizer.dart:182
E/flutter (19436): #9 TapGestureRecognizer._checkUp
package:flutter/…/gestures/tap.dart:365
E/flutter (19436): #10 TapGestureRecognizer.handlePrimaryPointer
package:flutter/…/gestures/tap.dart:275
E/flutter (19436): #11 PrimaryPointerGestureRecognizer.handleEvent
package:flutter/…/gestures/recognizer.dart:455
E/flutter (19436): #12 PointerRouter._dispatch
package:flutter/…/gestures/pointer_router.dart:75
E/flutter (19436): #13 PointerRouter.route
package:flutter/…/gestures/pointer_router.dart:102
E/flutter (19436): #14 GestureBinding.handleEvent
package:flutter/…/gestures/binding.dart:218
E/flutter (19436): #15 GestureBinding.dispatchEvent
package:flutter/…/gestures/binding.dart:198
E/flutter (19436): #16 GestureBinding._handlePointerEvent
package:flutter/…/gestures/binding.dart:156
E/flutter (19436): #17 GestureBinding._flushPointerEventQueue
package:flutter/…/gestures/binding.dart:102
E/flutter (19436): #18 GestureBinding._handlePointerDataPacket
package:flutter/…/gestures/binding.dart:86
E/flutter (19436): #19 _rootRunUnary (dart:async/zone.dart:1136:13)
E/flutter (19436): #20 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
E/flutter (19436): #21 _CustomZone.runUnaryGuarded (dart:async/zone.dart:931:7)
E/flutter (19436): #22 _invoke1 (dart:ui/hooks.dart:263:10)
E/flutter (19436): #23 _dispatchPointerDataPacket (dart:ui/hooks.dart:172:5)
E/flutter (19436):
Database's rules are the public ones:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
Can someone tell me what am I doing wrong?
According to docs just change your main method:
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
For who come here, I solved the problem. There is a lot of stuff to do, such as add your app to your Firebase project and edit some files.
The only thing to do is to read better the docs and follow all the steps:
Add Firebase to your Flutter app
All Firebase versions have been updated and now you have to call Firebase.initializeApp() before using any Firebase product, for example:
First, all Firebase products now depend on firebase_core version (0.5.0+), therefore you need to add it in the pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
firebase_core : ^0.5.0
Then you have to call Firebase.initializeApp():
In the main.dart:
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(); //Make sure you imported firebase_core
runApp(MaterialApp(
home: GettingStartedPage(),
));
}
import 'package:firebase_core/firebase_core.dart';
Add the apply plugin to the [project]/android/app/build.gradle file.
apply plugin: 'com.google.gms.google-services'
Add this at root gradle in android/build.gradle
classpath 'com.google.gms:google-services:4.3.5'
check https://github.com/flutter/plugins/blob/master/packages/firebase_auth/README.md