FLUTTER Error: MissingPluginException(No implementation found for method getApplicationDocumentsDirectory on channel plugins.flutter.io/path_provider) - flutter

I got this problem when I use NoSQL Hive and in the pubspec.yaml file I set upped the path_provider package.
I ran the flutter pub get and tried to reinstall all packages and flutter clean but it's still got this error.
Error: MissingPluginException(No implementation found for method getApplicationDocumentsDirectory on channel plugins.flutter.io/path_provider)
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 266:49 throw_
packages/flutter/src/services/platform_channel.dart 313:7 _invokeMethod
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 45:50 <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/zone.dart 1660:54 runUnary
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 147:18 handleValue
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 767:44 handleValueCallback
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 796:13 _propagateToListeners
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 567:5 [_completeWithValue]
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 640:7 callback
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/schedule_microtask.dart 40:11 _microtaskLoop
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/schedule_microtask.dart 49:5 _startMicrotaskLoop
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 166:15 <fn>
This is my main file:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
var directory = await getApplicationDocumentsDirectory();
Hive.init(directory.path);
runApp(
DevicePreview(
enabled: !kReleaseMode,
builder: (context) => MyApp(), // Wrap your app
),
);
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
useInheritedMediaQuery: true,
locale: DevicePreview.locale(context),
builder: DevicePreview.appBuilder,
home: HomeScreen(),
);
}
}

Related

Flutter code doesn't run when firebase is initialized

So I have this code when I run it without initializing firebase; it works, but once I initialize firebase on the main.dart, it returns a black screen and some error:
Error:
Error: Assertion failed:
file:///C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-2.0.2/lib/src/firebase_core_web.dart:228:11
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/\_internal/js_dev_runtime/private/ddc_runtime/errors.dart 266:49 throw\_
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/\_internal/js_dev_runtime/private/ddc_runtime/errors.dart 29:3 assertFailed
packages/firebase_core_web/src/firebase_core_web.dart 228:18 initializeApp
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/\_internal/js_dev_runtime/patch/async_patch.dart 45:50 \<fn\>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/zone.dart 1653:54 runUnary
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 147:18 handleValue
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 766:44 handleValueCallback
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 795:13
\_propagateToListeners
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 566:5 \[\_completeWithValue\]C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future.dart 528:22 \<fn\>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/zone.dart 1653:54 runUnary
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 147:18 handleValue
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 766:44 handleValueCallback
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 795:13
\_propagateToListeners
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 566:5 \[\_completeWithValue\]C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 639:7 callback
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/schedule_microtask.dart 40:11 \_microtaskLoop
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/schedule_microtask.dart 49:5 \_startMicrotaskLoop
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/\_internal/js_dev_runtime/patch/async_patch.dart 166:15 \<fn\>
Here is the code:
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:snow_chat/splash_screen.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]).then((_) {
runApp(const MyApp());
});
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
// ignore: prefer_const_constructors
return ScreenUtilInit(
designSize: const Size(375, 812),
minTextAdapt: true,
splitScreenMode: true,
builder: (context, child) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Chat app',
theme:
ThemeData(primaryColor: const Color.fromRGBO(88, 110, 158, 1)),
home: const SplashScreen(),
);
});
}
}
I have not tried anything cause I have not found a solution on how to fix this issue. Can someone please help out?
Make sure you are using flutterfire configure cmd to proper firebase setup in your flutter project
follow the steps given there
https://firebase.google.com/docs/flutter/setup?platform=android
https://firebase.google.com/docs/flutter/setup?platform=ios
Step 3.3 in the docs includes the options. Without this I believe it works for ios for example, but for web it throws your exception.
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);

Google SignIn Flutter Error: Assertion Failed

I am creating a fLutter app and I am trying to login using Firebase google_sign_in. But I am getting some error: Assertion Failed
That's my function:
void signInWithGoogle() async {
final GoogleSignIn _googleSignIn = GoogleSignIn();
try {
GoogleSignInAccount? account = await _googleSignIn.signIn();
if (account != null) {
final GoogleSignInAuthentication _authAccount =
await account.authentication;
final AuthCredential _credential = GoogleAuthProvider.credential(
idToken: _authAccount.idToken,
accessToken: _authAccount.accessToken,
);
UserCredential userCredential =
await _auth.signInWithCredential(_credential);
userCredential.user;
await saveUser(account);
}
} on Exception catch (error) {
AppLogger.e(error);
}
}
saveUser(GoogleSignInAccount account) {
userRf.doc(account.email).set({
"email": account.email,
"name": account.displayName,
"profilepic": account.photoUrl,
});
}
Error: Assertion failed:
..\…\lib\google_sign_in_web.dart:89
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 266:49 throw_
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 29:3 assertFailed
packages/google_sign_in_web/google_sign_in_web.dart 89:20 initWithParams
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 84:54 runBody
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 123:5 _async
packages/google_sign_in_web/google_sign_in_web.dart 86:30 initWithParams
packages/google_sign_in/google_sign_in.dart 290:39 [_ensureInitialized]
packages/google_sign_in/google_sign_in.dart 271:11 _callMethod
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 84:54 runBody _addMethodCall <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/pointer_binding.dart 594:14 <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/pointer_binding.dart 288:16 loggedHandler
C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/pointer_binding.dart 179:80 <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 334:14 _checkAndCall
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 339:39 dcall
I am new to Flutter. Please help me out.

Unhandled Exception: setState() called after dispose()

I am trying to receive notifications in my flutter app using Firebase Messaging to display them in the app, but I keep getting the error:
/FLTFireMsgReceiver( 6823): broadcast received for message
E/flutter ( 6823): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: setState() called after dispose(): _TipsState#aa4df(lifecycle state: defunct, not mounted)
E/flutter ( 6823): 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 ( 6823): 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 ( 6823): 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 ( 6823): #0 State.setState.<anonymous closure> (package:flutter/src/widgets/framework.dart:1085:9)
E/flutter ( 6823): #1 State.setState (package:flutter/src/widgets/framework.dart:1120:6)
E/flutter ( 6823): #2 _TipsState.getNotification.<anonymous closure> (package:stock_baba/Screens/Tips.dart:38:9)
E/flutter ( 6823): #3 _rootRunUnary (dart:async/zone.dart:1434:47)
E/flutter ( 6823): #4 _CustomZone.runUnary (dart:async/zone.dart:1335:19)
E/flutter ( 6823): #5 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1244:7)
E/flutter ( 6823): #6 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)
E/flutter ( 6823): #7 _DelayedData.perform (dart:async/stream_impl.dart:591:14)
E/flutter ( 6823): #8 _StreamImplEvents.handleNext (dart:async/stream_impl.dart:706:11)
E/flutter ( 6823): #9 _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:663:7)
E/flutter ( 6823): #10 _rootRun (dart:async/zone.dart:1418:47)
E/flutter ( 6823): #11 _CustomZone.run (dart:async/zone.dart:1328:19)
E/flutter ( 6823): #12 _CustomZone.runGuarded (dart:async/zone.dart:1236:7)
E/flutter ( 6823): #13 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1276:23)
E/flutter ( 6823): #14 _rootRun (dart:async/zone.dart:1426:13)
E/flutter ( 6823): #15 _CustomZone.run (dart:async/zone.dart:1328:19)
E/flutter ( 6823): #16 _CustomZone.runGuarded (dart:async/zone.dart:1236:7)
E/flutter ( 6823): #17 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1276:23)
E/flutter ( 6823): #18 _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
E/flutter ( 6823): #19 _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)
The PushNotification class is a simple class with the string fields title, body, dataTitle and dataBody.
My code is as follows:
class _TipsState extends State<Tips> {
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
final List<PushNotification> messages = [];
PushNotification? _notificationInfo;
#override
void initState() {
getNotification();
super.initState();
}
void getNotification() async {
NotificationSettings settings =
await _firebaseMessaging.requestPermission();
if (settings.authorizationStatus == AuthorizationStatus.authorized) {
print("Permission granted!");
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
PushNotification notification = PushNotification(
title: message.notification?.title,
body: message.notification?.body,
dataTitle: message.data['title'],
dataBody: message.data['body']);
setState(() {
_notificationInfo = notification;
});
if (notification != null) {
showSimpleNotification(Text(_notificationInfo!.title!),
duration: Duration(seconds: 2),
subtitle: Text(_notificationInfo!.body!));
}
print(notification);
print(message.data);
});
} else {
print("Permission declined!");
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: messages.isEmpty
? Container()
: ListView(
children: [Text(messages[0].title!)],
),
);
}
}
I tried wrapping my setState() with mounted() but it didn't work.
How can I resolve this issue and display the incoming notifications in my app?
Cancel the Stream after dispose it
Create StreamSubscription variable
StreamSubscription messagingSubscription;
Assign variable to your listen
....
messagingSubscription = FirebaseMessaging.onMessage.listen((RemoteMessage message) {
Dispose your StreamSubscription
#override
void dispose() {
messagingSubscription?.cancel();
super.dispose();
}
here is my code and its in working ..copy the code and make a dart class and paste it . your notification start working
use there plugins
firebase_core: ^1.11.0
firebase_messaging: ^11.2.5
flutter_local_notifications: ^9.2.0
import 'dart:convert';
import 'dart:math';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:vcare/firebase_options.dart';
class NotificationHelper {
NotificationDetails get _ongoing {
const androidChannelSpecifics = AndroidNotificationDetails(
'customer-channel-id',
'customer-channel-name',
importance: Importance.max,
priority: Priority.high,
ongoing: false,
autoCancel: true,
);
const iOSChannelSpecifics = IOSNotificationDetails();
return const NotificationDetails(android: androidChannelSpecifics, iOS: iOSChannelSpecifics);
}
// Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// If you're going to use other Firebase services in the background, such as Firestore,
// make sure you call `initializeApp` before using other Firebase services.
// await initFirebase();
// }
configure() async {
await initFirebase();
FirebaseMessaging messaging = FirebaseMessaging.instance;
await requestPermission(messaging);
final String? token = await messaging.getToken();
// FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
final notification = await setupLocalNotification();
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
showNotification(
notification,
title: message.notification?.title,
body: message.notification?.body,
payload: message.data,
type: _ongoing,
);
});
return token;
}
Future<void> requestPermission(FirebaseMessaging messaging) async {
await messaging.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: true,
);
}
Future<void> initFirebase() async {
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
}
setupLocalNotification() async {
const AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings(
'notification_icon',
);
final IOSInitializationSettings initializationSettingsIOS = IOSInitializationSettings(
onDidReceiveLocalNotification: (int id, String? title, String? body, String? payload) {},
);
final InitializationSettings initializationSettings = InitializationSettings(
android: initializationSettingsAndroid,
iOS: initializationSettingsIOS,
);
var notification = FlutterLocalNotificationsPlugin();
await notification.initialize(initializationSettings, onSelectNotification: (_) {});
return notification;
}
showNotification(FlutterLocalNotificationsPlugin notifications,
{required String? title, required String? body, required NotificationDetails type, required payload}) {
notifications.show(Random().nextInt(100), title, body, type, payload: json.encode(payload ?? {}));
}
}
and then call this class in main.dart file here is the code
WidgetsFlutterBinding.ensureInitialized();
String? token = await NotificationHelper().configure();
_storeFCMToken(token);
print("deviceToken $token");
if you find any problem please let me know. if you find this code is helping you .then please mark my answer as accepted

Unhandled Exception: MissingPluginException when running Flutter app with sqflite

I'm trying to use SQLite database using the sqflite plugin. Running the app below results in Unhandled Exception: MissingPluginException error.
Here's my code:
main.dart:
...
late final Database database;
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
database = await openDatabase(
join(await getDatabasesPath(), 'mydb.db'),
version: 1,
onCreate: (db, version) {
return db.execute('CREATE TABLE config(key TEXT PRIMARY KEY, value TEXT)');
},
);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
title: 'MyApp',
initialRoute: '/',
onGenerateRoute: (settings) => onGenerateRoute(settings),
onUnknownRoute: pageNotImplementedRoute,
);
}
}
Route? onGenerateRoute(RouteSettings settings) {
...
}
Route pageNotImplementedRoute(RouteSettings settings) {
return MaterialPageRoute<void>(...);
}
Here's the output from the run:
Launching lib\main.dart on Android SDK built for x86 64 in debug mode...
Running Gradle task 'assembleDebug'...
? Built build\app\outputs\flutter-apk\app-debug.apk.
Installing build\app\outputs\flutter-apk\app.apk...
Debug service listening on ws://127.0.0.1:56398/fJzrmThsqQA=/ws
Syncing files to device Android SDK built for x86 64...
E/flutter ( 6173): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: MissingPluginException(No implementation found for method getDatabasesPath on channel com.tekartik.sqflite)
E/flutter ( 6173): #0 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:154:7)
E/flutter ( 6173): <asynchronous suspension>
E/flutter ( 6173): #1 wrapDatabaseException (package:sqflite/src/exception_impl.dart:7:20)
E/flutter ( 6173): <asynchronous suspension>
E/flutter ( 6173): #2 SqfliteDatabaseFactoryMixin.getDatabasesPath (package:sqflite_common/src/factory_mixin.dart:152:20)
E/flutter ( 6173): <asynchronous suspension>
E/flutter ( 6173): #3 main (package:mymedica/main.dart:76:10)
E/flutter ( 6173): <asynchronous suspension>
E/flutter ( 6173):
Anyone has any idea what's wrong?
This error is just because the SQFLite dependency not get it's package. you should follow this steps. It's Work for me...
flutter clean
File > Invalide caches & Restart
flutter pub get
And you will get your desired outcome.!

Exception caught by flutter test framework

I have the following widget tests, when I run nothing test the test passes normally, but when I run all the main I have an error.
The test I have corresponds to the following:
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
testWidgets('initial status of login page', (WidgetTester tester) async {
Widget widget = LoginPage();
await tester.pumpWidget(MaterialApp(
navigatorKey: navigatorKey,
scaffoldMessengerKey: scaffoldMessengerKey,
home: widget,
locale: Locale('en'),
supportedLocales: lang.getSupportedLocales(),
localizationsDelegates: lang.localizationsDelegates,
localeResolutionCallback: lang.getLocaleResolutionCallback,
));
await tester.pumpAndSettle();
expect(find.text(lang.translate('login.welcome')), findsOneWidget);
});
testWidgets('enter an invalid email', (WidgetTester tester) async {
Widget widget = LoginPage();
await tester.pumpWidget(MaterialApp(
navigatorKey: navigatorKey,
scaffoldMessengerKey: scaffoldMessengerKey,
home: widget,
locale: Locale('en'),
supportedLocales: lang.getSupportedLocales(),
localizationsDelegates: lang.localizationsDelegates,
localeResolutionCallback: lang.getLocaleResolutionCallback,
));
await tester.pumpAndSettle();
final Finder emailInputFinder = find.byKey(Key('emailInput'));
final Finder passwordInputFinder = find.byKey(Key('passwordInput'));
final Finder signInButtonFinder = find.byKey(Key('signInButton'));
await tester.tap(emailInputFinder);
await tester.enterText(emailInputFinder, 'email');
await tester.pumpAndSettle();
await tester.enterText(passwordInputFinder, 'password');
await tester.pumpAndSettle();
expect(signInButtonFinder, findsNothing);
});
}
The error that while in the console is:
✓ initial status of login page
══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following StateError was thrown running a test:
Bad state: No element
When the exception was thrown, this was the stack:
#0 Iterable.single (dart:core/iterable.dart:498:25)
#1 WidgetController._getElementPoint (package:flutter_test/src/controller.dart:814:47)
#2 WidgetController.getCenter (package:flutter_test/src/controller.dart:786:12)
#3 WidgetController.tap (package:flutter_test/src/controller.dart:257:18)
#4 main.<anonymous closure> (file:///Users/ezequiel/Documents/Larvia/lrv-mobile-app/test/widget_test/login2_test.dart:45:18)
<asynchronous suspension>
<asynchronous suspension>
(elided one frame from package:stack_trace)
The test description was:
enter an invalid email
════════════════════════════════════════════════════════════════════════════════════════════════════
Test failed. See exception logs above.
The test description was: enter an invalid email
Please I need help, if you have any ideas I thank you for your time.