java.lang.NoClassDefFoundError: de.mintware.barcode_scan.Protos$Configuration - flutter

i'm trying to develop an app and adding a barcode scanner to track the the food eaten, but every time i run i've got the errors from barcode:scan:
E/flutter ( 5352): Caused by: java.lang.NoClassDefFoundError: de.mintware.barcode_scan.Protos$Configuration
E/flutter ( 5352):de.mintware.barcode_scan.ChannelHandler.onMethodCall(ChannelHandler.kt:111)
E/flutter ( 5352): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:262)
E/flutter ( 5352): at io.flutter.embedding.engine.dart.DartMessenger.invokeHandler(DartMessenger.java:296)
E/flutter ( 5352): at io.flutter.embedding.engine.dart.DartMessenger.lambda$dispatchMessageToQueue$0$io-flutter-embedding-engine-dart-DartMessenger(DartMessenger.java:320)
E/flutter ( 5352): at io.flutter.embedding.engine.dart.DartMessenger$$ExternalSyntheticLambda0.run(Unknown Source:12)
E/flutter ( 5352): at android.os.Handler.handleCallback(Handler.java:938)
E/flutter ( 5352): at android.os.Handler.dispatchMessage(Handler.java:99)
E/flutter ( 5352): at android.os.Looper.loopOnce(Looper.java:201)
E/flutter ( 5352): at android.os.Looper.loop(Looper.java:288)
E/flutter ( 5352): at android.app.ActivityThread.main(ActivityThread.java:7842)
E/flutter ( 5352): at java.lang.reflect.Method.invoke(Native Method)
E/flutter ( 5352): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
E/flutter ( 5352): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
E/flutter ( 5352): Caused by: java.lang.NoClassDefFoundError: de.mintware.barcode_scan.Protos$Configuration
E/flutter ( 5352): at de.mintware.barcode_scan.Protos$Configuration.newBuilder(Protos.java:1357)
E/flutter ( 5352): at de.mintware.barcode_scan.ChannelHandler.scan(ChannelHandler.kt:27)
my android/build.gradle is:
buildscript {
ext.kotlin_version = '1.6.20'
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.google.gms:google-services:4.3.10'
classpath 'com.android.tools.build:gradle:7.3.0-alpha04'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "com.google.protobuf:protobuf-gradle-plugin:0.8.13"
classpath 'com.android.tools.build:gradle:4.3.8'
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Let me know how can i fix it

Related

simple push notification but its not working and its throwing an error

im trying to display a push notification by clicking a text button but then it throws this error i tried to search but couldnt fix it, i tried reinstalling the app and also restarted the app multiple times
E/flutter ( 8853): at android.os.Handler.handleCallback(Handler.java:938)
E/flutter ( 8853): at android.os.Handler.dispatchMessage(Handler.java:99)
E/flutter ( 8853): at android.os.Looper.loop(Looper.java:223)
E/flutter ( 8853): at android.app.ActivityThread.main(ActivityThread.java:7656)
E/flutter ( 8853): at java.lang.reflect.Method.invoke(Native Method)
E/flutter ( 8853): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
E/flutter ( 8853): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
E/flutter ( 8853): )
E/flutter ( 8853): #0 StandardMethodCodec.decodeEnvelope
package:flutter/…/services/message_codecs.dart:653
E/flutter ( 8853): #1 MethodChannel.\_invokeMethod
package:flutter/…/services/platform_channel.dart:296
E/flutter ( 8853): \<asynchronous suspension\>
E/flutter ( 8853): #2 FlutterLocalNotificationsPlugin.show
package:flutter_local_notifications/src/flutter_local_notifications_plugin.dart:234
E/flutter ( 8853): \<asynchronous suspension\>
E/flutter ( 8853):
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
class NotificationApi {
static final _notification = FlutterLocalNotificationsPlugin();
static Future _notificationDetails() async {
return const NotificationDetails(
android: AndroidNotificationDetails(
'channel id'
'channel name',
'channel description',
importance: Importance.high,
),
iOS: DarwinNotificationDetails(),
);
}
static Future showNotification({
int id = 0,
String? title,
String? body,
String? payload,
}) async =>
_notification.show(id, title, body, await _notificationDetails(),
payload: payload);
}
flutter_local_notifications: ^12.0.3+1

Google Mobile Ads Throwing MissingPluginException

RewardedAd doesn't work on google_mobile_ads: 2.0.1
I've already searched everywhere and the fixes don't work.
This is the Error on The Logs.
E/DartMessenger( 5002): Uncaught exception in binary message listener
E/DartMessenger( 5002): java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Map
E/DartMessenger( 5002): at io.flutter.plugins.googlemobileads.AdMessageCodec.readValueOfType(AdMessageCodec.java:231)
E/DartMessenger( 5002): at io.flutter.plugin.common.StandardMessageCodec.readValue(StandardMessageCodec.java:340)
E/DartMessenger( 5002): at io.flutter.plugin.common.StandardMessageCodec.readValueOfType(StandardMessageCodec.java:434)
E/DartMessenger( 5002): at io.flutter.plugins.googlemobileads.AdMessageCodec.readValueOfType(AdMessageCodec.java:319)
E/DartMessenger( 5002): at io.flutter.plugin.common.StandardMessageCodec.readValue(StandardMessageCodec.java:340)
E/DartMessenger( 5002): at io.flutter.plugin.common.StandardMethodCodec.decodeMethodCall(StandardMethodCodec.java:51)
E/DartMessenger( 5002): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:260)
E/DartMessenger( 5002): at io.flutter.embedding.engine.dart.DartMessenger.invokeHandler(DartMessenger.java:295)
E/DartMessenger( 5002): at io.flutter.embedding.engine.dart.DartMessenger.lambda$dispatchMessageToQueue$0$DartMessenger(DartMessenger.java:319)
E/DartMessenger( 5002): at io.flutter.embedding.engine.dart.-$$Lambda$DartMessenger$TsixYUB5E6FpKhMtCSQVHKE89gQ.run(Unknown Source:12)
E/DartMessenger( 5002): at android.os.Handler.handleCallback(Handler.java:883)
E/DartMessenger( 5002): at android.os.Handler.dispatchMessage(Handler.java:100)
E/DartMessenger( 5002): at android.os.Looper.loop(Looper.java:237)
E/DartMessenger( 5002): at android.app.ActivityThread.main(ActivityThread.java:7830)
E/DartMessenger( 5002): at java.lang.reflect.Method.invoke(Native Method)
E/DartMessenger( 5002): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
E/DartMessenger( 5002): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1040)
E/flutter ( 5002): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: MissingPluginException(No implementation found for method loadRewardedAd on channel plugins.flutter.io/google_mobile_ads)
E/flutter ( 5002): #0 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:165:7)
E/flutter ( 5002): <asynchronous suspension>
E/flutter ( 5002): #1 RewardedAd.load (package:google_mobile_ads/src/ad_containers.dart:1154:5)
E/flutter ( 5002): <asynchronous suspension>
E/flutter ( 5002):
I already Ad this code on MainActivity
override fun configureFlutterEngine(#NonNull flutterEngine: FlutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine);
}
I made sure also to put this on build.gradle
implementation 'com.google.android.gms:play-services-ads:21.1.0'
I also add this to manifest file
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-3940256099942544~3347511713" />
This is my implementation
I added this on my main
final initFuture = MobileAds.instance.initialize();
final adState = AdState(initFuture);
And Created another File for AdState
static String get rewardedAdUnitId {
if (Platform.isAndroid) {
return "ca-app-pub-3940256099942544/5224354917";
} else if (Platform.isIOS) {
return "ca-app-pub-3940256099942544/1712485313";
} else {
throw new UnsupportedError("Unsupported platform");
}
}
Future initialization;
AdState(this.initialization);
On my Implementation
void loadRewardedAd(BuildContext context) {
RewardedAd.load(
adUnitId: AdState.rewardedAdUnitId,
request: const AdRequest(),
rewardedAdLoadCallback:
RewardedAdLoadCallback(onAdLoaded: (ad) {
ad.show(
onUserEarnedReward: (ad,rewardPoints){
CommonTools.showMessage(context, 'Energy Received : ');
}
);
ad.fullScreenContentCallback = FullScreenContentCallback(
onAdShowedFullScreenContent: (ad){
},
onAdFailedToShowFullScreenContent: (ad,error){
CommonTools.showMessage(context, 'Ads Not Available For Now');
ad.dispose();
},
onAdDismissedFullScreenContent: (ad){
CommonTools.showMessage(context, 'Ads Not Available For Now');
ad.dispose();
}
);
}, onAdFailedToLoad: (er) {
CommonTools.showMessage(context, 'Ads Not Available For Now');
}));
}
After making this issue traumatize me I managed to make it work. What I did is wrap everything in MaterialApp and put routes on my main Widget.
runApp(
MaterialApp(
routes: <String, WidgetBuilder>{
'/': (BuildContext context) => MyApp()
},
),
);
As for how this works, I don't know how it fix everything but it might help you if you encounter this issue.
The above Main Activity code is for kotlin. Make sure your Main Activity is also in Kotlin.

Can't play sound in Flutter Android using just_audio

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.

cant get downloadUrl after upload the image to FireBase in Flutter

after i upload my image to Firebase i cant get it's download url. i wanna get it to show uploaded pics in other pages. here is my codes:
import 'dart:io';
import 'package:firebase/GetPic.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
class ImageUploadPage extends StatefulWidget {
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return ImageUploadPageState();
}
}
class ImageUploadPageState extends State{
TextEditingController _control= TextEditingController();
File _selectedImage;
final _formKey = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBar(
title: Text("IMAGE UPLOAD PAGE"),
actions: [
IconButton(
icon: Icon(Icons.arrow_right_alt), onPressed: (){
Navigator.push(context, MaterialPageRoute(
builder: (context)=>GetPic(),));
}),
],
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
RaisedButton(
child: Text("Galeriden resim seçin"),
onPressed: (){_selectImage();}),
Expanded(
child: _selectedImage== null ?
Text("there is no pic"): Image.file(_selectedImage)),
Form(
key: _formKey,
child: Padding(
padding: const EdgeInsets.all(25.0),
child: TextFormField(
controller: _control,
decoration: InputDecoration(
labelText: "image's name",
labelStyle: TextStyle(color: Colors.greenAccent)
),
style: TextStyle(fontStyle: FontStyle.italic, fontSize: 17),
),
),
),
RaisedButton(
child: Text("Upload image"),
onPressed: (){_uploadImage();}),
]
),
),
);
}
void _selectImage() async {
var _iamge= await ImagePicker.pickImage(source: ImageSource.gallery);
_selelctedImage= _image;
setState(() {});
}
Future<String> _uploadImage() async {
_formKey.currentState.save();
String imageFileName = _control.text;
final Reference ref = await FirebaseStorage.instance.ref().child("deneme").child("resimler").child(imageFileName);
UploadTask uploadTask = ref.putFile(_selectedImage);
var downloadUrl = await (await uploadTask.snapshot).ref.getDownloadURL();
debugPrint(downloadUrl.toString());
return downloadUrl.toString();
}
}
i have TextFormField that gives image's name. if i upload an image(same or different) with same name i can get last one's donwload url normally. in my opinion image's name that i uploaded cant be seen at first try unlike to second try. so i am fail to get download url at first try and success at second try. i hope i could tell my problem clearly. i will be so glad if somebody helps.
Here is my android/build.gradle
buildscript {
ext.kotlin_version = '1.3.50'
repositories {
google() // Google's Maven repository
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.0.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.google.gms:google-services:4.3.4'
classpath 'com.google.firebase:firebase-crashlytics-gradle:2.4.1'
}
}
allprojects {
repositories {
google() // Google's Maven repository
jcenter()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Here is my app/build.gradle
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
apply plugin: 'com.google.firebase.crashlytics'
android {
compileSdkVersion 29
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
lintOptions {
disable 'InvalidPackage'
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "meb.firebase"
minSdkVersion 16
targetSdkVersion 29
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
}
}
}
flutter {
source '../..'
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.4.20"
testImplementation 'junit:junit:4.13.1'
androidTestImplementation 'androidx.test:runner:1.3.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation platform('com.google.firebase:firebase-bom:26.1.0')
implementation 'com.android.support:multidex:1.0.3'
implementation "com.google.firebase:firebase-messaging:20.2.4"
}
and al last Here is my error message:
E/flutter (17095): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: [firebase_storage/object-not-found] No object exists at the desired reference.
E/flutter (17095): #0 MethodChannelReference.getDownloadURL (package:firebase_storage_platform_interface/src/method_channel/method_channel_reference.dart:57:7)
E/flutter (17095): <asynchronous suspension>
E/flutter (17095): #1 Reference.getDownloadURL (package:firebase_storage/src/reference.dart:94:48)
E/flutter (17095): #2 ImageUploadPageState._resimYukle (package:firebase/ImageUploadPage.dart:83:61)
E/flutter (17095): <asynchronous suspension>
E/flutter (17095): #3 ImageUploadPageState.build.<anonymous closure> (package:firebase/ImageUploadPage.dart:62:31)
E/flutter (17095): #4 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:993:19)
E/flutter (17095): #5 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:1111:38)
E/flutter (17095): #6 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:183:24)
E/flutter (17095): #7 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:598:11)
E/flutter (17095): #8 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:287:5)
E/flutter (17095): #9 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:222:7)
E/flutter (17095): #10 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:476:9)
E/flutter (17095): #11 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:77:12)
E/flutter (17095): #12 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:122:9)
E/flutter (17095): #13 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:377:8)
E/flutter (17095): #14 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:120:18)
E/flutter (17095): #15 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:106:7)
E/flutter (17095): #16 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:358:19)
E/flutter (17095): #17 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:338:22)
E/flutter (17095): #18 RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:267:11)
E/flutter (17095): #19 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:295:7)
E/flutter (17095): #20 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:240:7)
E/flutter (17095): #21 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:213:7)
E/flutter (17095): #22 _rootRunUnary (dart:async/zone.dart:1206:13)
E/flutter (17095): #23 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter (17095): #24 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
E/flutter (17095): #25 _invoke1 (dart:ui/hooks.dart:265:10)
E/flutter (17095): #26 _dispatchPointerDataPacket (dart:ui/hooks.dart:174:5)
E/flutter (17095):
Just await the result of putFile to wait until the upload is complete before requesting the URL.
await ref.putFile(_selectedImage);
var downloadUrl = await ref.getDownloadURL();
debugPrint(downloadUrl);
I suggest reviewing the documentation for more details.

Flutter method channel error. { Unhandled Exception: MissingPluginException(No implementation found for method getBatteryLevel on channel battery) }

so i followed everthing from 'https://flutter.dev/docs/development/platform-integration/platform-channels?tab=android-channel-java-tab' but when I click the floating button in my device this error is shown.
[ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: MissingPluginException(No implementation found for method getBatteryLevel on channel battery)
E/flutter ( 4580): #0 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:159:7)
E/flutter ( 4580): <asynchronous suspension>
E/flutter ( 4580): #1 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:334:12)
E/flutter ( 4580): #2 _batteryState._getBatteryLevel (package:flutter_app/main.dart:45:37)
E/flutter ( 4580): #3 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:992:19)
E/flutter ( 4580): #4 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:1098:38)
E/flutter ( 4580): #5 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:184:24)
E/flutter ( 4580): #6 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:524:11)
E/flutter ( 4580): #7 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:284:5)
E/flutter ( 4580): #8 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:219:7)
E/flutter ( 4580): #9 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:477:9)
E/flutter ( 4580): #10 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:78:12)
E/flutter ( 4580): #11 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:124:9)
E/flutter ( 4580): #12 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:377:8)
E/flutter ( 4580): #13 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:122:18)
E/flutter ( 4580): #14 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:108:7)
E/flutter ( 4580): #15 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:220:19)
E/flutter ( 4580): #16 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:200:22)
E/flutter ( 4580): #17 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:158:7)
E/flutter ( 4580): #18 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:104:7)
E/flutter ( 4580): #19 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:88:7)
E/flutter ( 4580): #20 _rootRunUnary (dart:async/zone.dart:1206:13)
E/flutter ( 4580): #21 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter ( 4580): #22 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
E/flutter ( 4580): #23 _invoke1 (dart:ui/hooks.dart:267:10)
E/flutter ( 4580): #24 _dispatchPointerDataPacket (dart:ui/hooks.dart:176:5)
E/flutter ( 4580):
Main.dart:-
import 'dart:ffi';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main(){
runApp(
MaterialApp(
home: battery()
)
);
}
class battery extends StatefulWidget {
#override
_batteryState createState() => _batteryState();
}
class _batteryState extends State<battery> {
static const platform = const MethodChannel('battery');
String _batteryLevel = 'error';
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('BatteryDetails'),
),
body: Center(
child: Column(
children: <Widget>[
FloatingActionButton.extended(onPressed: _getBatteryLevel, label: Text('Get battery info')),
Text(_batteryLevel),
],
)
)
);
}
Future<void> _getBatteryLevel() async{
String BatteryLevel;
try {
final int result = await platform.invokeMethod('getBatteryLevel');
BatteryLevel = 'battery Level is $result %.';
}on PlatformException catch (e){
BatteryLevel = "failed to get battery level: '&{e.message}'";
}
setState(() {
_batteryLevel = BatteryLevel;
});
}
}
MainActivity.java:-
package com.example.flutter_app;
import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodChannel;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
public class MainActivity extends FlutterActivity {
private static final String CHANNEL = "battery";
#Override
public void configureFlutterEngine(#NonNull FlutterEngine flutterEngine) {
super.configureFlutterEngine(flutterEngine);
new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
.setMethodCallHandler(
(call, result) -> {
// Note: this method is invoked on the main thread.
if (call.method.equals("getBatteryLevel")) {
int batteryLevel = getBatteryLevel();
if (batteryLevel != -1) {
result.success(batteryLevel);
} else {
result.error("UNAVAILABLE", "Battery level not available.", null);
}
} else {
result.notImplemented();
}
}
);
}
private int getBatteryLevel() {
int batteryLevel = -1;
if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
BatteryManager batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE);
batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
} else {
Intent intent = new ContextWrapper(getApplicationContext()).
registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
batteryLevel = (intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100) /
intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
}
return batteryLevel;
}
}
i am new to flutter, can you help me also can anyone explain me what is happening in
public void configureFlutterEngine(#NonNull FlutterEngine flutterEngine) {
super.configureFlutterEngine(flutterEngine);
new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
.setMethodCallHandler(
(call, result)
this part of code.
thank you.
Based from the the error you got, you're getting a MissingPluginException from the method getBatteryLevel. This means the app is unable to find the method you're trying to call.
If you just tried running the app using hot reload, changes on platform-specific code might have not registered. Running the app using restart should usually solve the issue. If you're still having issues, you can print the log of the call.method being passed to the MethodChannel in your MainActivity.java to see if the method name from Flutter is being received as expected.
When using native features, always add the required dependencies in either Info.plist or AndroidManifest.xml and always re-install the whole app, hot-restart/reload won't always work if you all of a sudden implement some new code that accesses native device features.