Flutter local notifications doesn't grant permissions on Android - android

flutter_local_notifications doesn't show permissions dialog on Android API level 33. Tested with emulator. In AndroidManifest.xml file, I've defined the needed permission:
This is an example code:
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
Future<void> setup() async {
final _localNotificationsPlugin = FlutterLocalNotificationsPlugin();
const androidSetting = AndroidInitializationSettings('#mipmap/ic_launcher');
const initSettings = InitializationSettings(android: androidSetting);
await _localNotificationsPlugin.initialize(initSettings).then((_) {
debugPrint('setupPlugin: setup success');
}).catchError((Object error) {
debugPrint('Error: $error');
});
bool? granted = await _localNotificationsPlugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()?.requestPermission() ?? false;
print('granted: $granted');
}
void main() {
WidgetsFlutterBinding.ensureInitialized();
setup();
runApp(myApp());
}
class myApp extends StatelessWidget {
myApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Container(
child: Text('Notification test')
)
)
);
}
}

Related

ThemeMode is null in debug console

I am implementing ThemeMode feature on my fluter app for example if user have saved ThemeMode (light, dark or system) saved in SharedPreferences then it should load on app startup otherwise bydefault it is light. so i am using Provider for state management.
Here is my approach:
on themes_provider.dart
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../utils/themes.dart';
class ThemesProvider extends ChangeNotifier {
ThemeMode? _themeMode;
ThemeMode? get themeMode => _themeMode;
ThemeData get lightTheme => ThemeManager().lightTheme;
ThemeData get darkTheme => ThemeManager().darkTheme;
void initThemeMode() async {
final _prefs = await SharedPreferences.getInstance();
final _currentTheme = _prefs.getString('theme') ?? 'light';
if (_currentTheme == 'light') {
_themeMode = ThemeMode.light;
} else if (_currentTheme == 'dark') {
_themeMode = ThemeMode.dark;
} else {
_themeMode = ThemeMode.system;
}
notifyListeners();
}
void setThemeMode(int value) async {
final _prefs = await SharedPreferences.getInstance();
_prefs.setInt('theme', value);
notifyListeners();
}
}
and then on main.dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => UserProvider()),
ChangeNotifierProvider(
create: (context) => ThemesProvider(),
)
],
builder: (context, snapshot) {
final _themeNotifier =
Provider.of<ThemesProvider>(context, listen: false);
_themeNotifier.initThemeMode();
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: _themeNotifier.lightTheme,
darkTheme: _themeNotifier.darkTheme,
themeMode: _themeNotifier.themeMode,
home: HomeScreen(),
onGenerateRoute: RouteGenerator.generateRoute,
initialRoute: RouteGenerator.loginRoute,
);
});
}
}
But in debug console i am getting null value on _themeNotifier.themeMode
please help.

fix net::err_unknown_url_scheme whatsapp link on flutter webview

Please I want to know how to launch WhatsApp in the Flutter webview app or launch WhatsApp from the browser in Flutter, have used many codes with no errors but they do not work.Am using mac m1
and vscode
import 'package:coinpaga/Connectivity_Provider.dart';
import 'package:coinpaga/services/local_notification_service.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'homepage.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:colorful_safe_area/colorful_safe_area.dart';
/// Receive message when app is in background solution for on
message
Future<void> backgroundHandler(RemoteMessage message)async{
print(message.data.toString());
print(message.notification!.title);
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
LocalNotificationServices.initialize();
await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage(backgroundHandler);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(
create: (context) => ConnectivityProvider(),
child: HomePage(),
)
],
child:MaterialApp(
title: 'coinpaga',
theme: ThemeData(
primarySwatch: Colors.blue,
),
debugShowCheckedModeBanner: false,
home: ColorfulSafeArea(
color: HexColor("#2e2a42"),
top: true,
bottom: false,
left: false,
right: false,
child: HomePage(),
)
),
);
}
}
Home.dart
import 'package:coinpaga/Connectivity_Provider.dart';
import 'package:coinpaga/no_internet.dart';
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:provider/provider.dart';
class HomePage extends StatefulWidget {
// ignore: unused_field
final _flutterwebview = FlutterWebviewPlugin();
HomePage({ Key? key }) : super(key: key);
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
void initState() {
super.initState();
Provider.of<ConnectivityProvider>(context, listen:
false).startMonitoring();
}
#override
Widget build(BuildContext context) {
return pageUI();
}
#override
void dispose() {
_flutterwebview.dispose();
super.dispose();
}
}
Widget pageUI() {
return Consumer<ConnectivityProvider>(
builder: (context, model, child) {
return model.isOnline
? WebviewScaffold(
url: 'https://coinpaga.com',
withLocalStorage: true,
withJavascript: true,
scrollBar: false,
initialChild: Center(child: Text('Loading...')),
) : NoInternet();
},
);
}
// ignore: camel_case_types
class _flutterwebview {
static void dispose() {}
}
Please help me go through it.
String text = "Hello World !! Hey There";
String url = "https://wa.me/?text=${Uri.encodeFull(text)}";
if (await canLaunchUrl(Uri.parse(url))) {
await launchUrl(Uri.parse(url),
mode: LaunchMode.externalApplication);
}
First, add url_launcher, then I use this code to launch whatsapp on flutter webview and works.
WebView(
initialUrl: getUrl(_url),
javascriptMode: JavascriptMode.unrestricted,
navigationDelegate: (NavigationRequest request) async {
if (request.url
.startsWith('https://api.whatsapp.com/send?phone')) {
print('blocking navigation to $request}');
List<String> urlSplitted = request.url.split("&text=");
String phone = "0123456789";
String message =
urlSplitted.last.toString().replaceAll("%20", " ");
await _launchURL(
"https://wa.me/$phone/?text=${Uri.parse(message)}");
return NavigationDecision.prevent;
}
print('allowing navigation to $request');
return NavigationDecision.navigate;
},
)
_launchURL(String url) async {
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
You can use url_launcher to launch URLs.
You can give https://api.whatsapp.com/send/?phone=(phone_number) URL to launch.
For the launching the WhatsApp Website use launch('https://api.whatsapp.com/send/?phone=(phone_number)')
Make sure you give your country code without (+).

Flutter QR Scan is not working after Camera Tab

My app has 2 bottom tabs first one is to capture an Image and second one is to scan QR code through camera.
for Camera i'm using camera: ^0.9.4+1 plugin and for QR code its scan: ^1.4.3 https://pub.dev/packages/scan
once app is restarted you can tap on QR code tab its working then tab on Camera its working too now again tapping on QR tab it shows some wired errors it seems camera not properly disposed or any thing.
import 'dart:io';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:snapi/controllers/home/home.controller.dart';
class CaptureTab extends StatefulWidget {
final List<CameraDescription> cameras;
const CaptureTab({Key? key, required this.cameras}) : super(key: key);
#override
_CaptureTabState createState() => _CaptureTabState();
}
class _CaptureTabState extends State<CaptureTab> {
Size size = Get.size;
final HomeController controller = Get.find();
#override
void initState() {
super.initState();
initializeCamera(0);
}
late CameraController _controller; //To control the camera
late Future<void> _initializeControllerFuture;
List<File> capturedImages = [];
initializeCamera(int cameraIndex) async {
_controller = CameraController(
widget.cameras[cameraIndex],
ResolutionPreset.medium,
);
_initializeControllerFuture = _controller.initialize();
}
#override
void dispose() {
super.dispose();
_controller.dispose();
}
#override
Widget build(BuildContext context) {
Size size = Get.size;
return Scaffold(
backgroundColor: Colors.white,
body: Stack(
children: [
SizedBox(
height: size.height - size.height * 0.076,
child: FutureBuilder<void>(
future: _initializeControllerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return CameraPreview(_controller);
} else {
return const Center(child: CircularProgressIndicator());
}
},
),
),
],
),
);
}
}
QR code scanning code.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:scan/scan.dart';
import 'package:snapi/controllers/home/home.controller.dart';
class ResourceTab extends StatefulWidget {
const ResourceTab({Key? key}) : super(key: key);
#override
State<StatefulWidget> createState() => _ResourceTabState();
}
class _ResourceTabState extends State<ResourceTab> {
String _platformVersion = 'Unknown';
final HomeController homeController = Get.find();
ScanController controller = ScanController();
String qrcode = 'Unknown';
#override
void initState() {
super.initState();
initPlatformState();
}
#override
void dispose() {
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
Expanded(
flex: 4,
child: ScanView(
controller: controller,
scanAreaScale: .7,
scanLineColor: Colors.green.shade400,
onCapture: (data) async {
// do something interesting
},
),
),
],
),
);
}
Future<void> initPlatformState() async {
String platformVersion;
try {
platformVersion = await Scan.platformVersion;
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}
if (!mounted) return;
setState(() {
_platformVersion = platformVersion;
});
}
}
The best explanation of error is look like this.
this is the error i got while opning QR scaning view after Camera preview.
E/CameraCaptureSession( 7546): Session 0: Exception while stopping repeating:
android.hardware.camera2.CameraAccessException: CAMERA_ERROR (3): cancelRequest:459: Camera 0: Error clearing streaming request: Function not implemented (-38)

How to implement multiple packages in main.dart in flutter?

I am developing one app in flutter-android, for that, I am using screenUtil package and also I am checking device connection status(internet). Now my main.dart code is below where I have initialized screenUtil
void main() => (runApp(new MyApp()));
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ScreenUtilInit(
designSize: Size(360, 690),
allowFontScaling: false,
builder: () => MaterialApp(
debugShowCheckedModeBanner: false,
home: HomeScreen(),
),
);
}
}
This is the code I need to use in my main.dart to get the connection status across my widgets:
void main() => (runApp(new MyApp()));
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return StreamProvider<ConnectivityStatus>(
builder: (context) => ConnectivityService().connectionStatusController,
child: MaterialApp(
debugShowCheckedModeBanner: false,
home: HomeScreen(),
),
);
}
How can I use both the codes in my main.dart file?
Example : internet connection check programmatically in flutter.
You can sync with my code.
like these my source code below in details. just copy and past then modify with yours code
it is main.dart file:
import 'package:connectivity/connectivity.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
void main() => (runApp(new MyApp()));
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ScreenUtilInit(
designSize: Size(360, 690),
builder: () => MaterialApp(
debugShowCheckedModeBanner: false,
home: HomeScreen(),
),
);
}
}
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
var connectionStatus="";
#override
void initState() {
// TODO: implement initState
super.initState();
checkConnection();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text(connectionStatus),
),
);
}
void checkConnection() async{
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile) {
// I am connected to a mobile network.
// write your code here;
connectionStatus="mobile data";
} else if (connectivityResult == ConnectivityResult.wifi) {
// I am connected to a wifi network.
// write your code here
connectionStatus="wifi data";
} else {
// where your code here
connectionStatus="no internet connection";
}
}
}
and my pubspec.yaml file
name: flutter_app
description: A new Flutter application.
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
flutter_screenutil: ^5.0.0
data_connection_checker: ^0.3.4
connectivity: ^3.0.2
connectivity_platform_interface: ^2.0.1
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
best of luck!

Firebase initializeApp before runApp in flutter takes a lot of time

My question is how to show a splash screen or alternatively show a loading screen if I execute the following code:
void main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
You can simply use Future Builder for that,
void main() async{
WidgetsFlutterBinding.ensureInitialized();
//remove this line from your code
//await Firebase.initializeApp();
runApp(MyApp());
}
this is code for MyApp()
class MyApp extends StatelessWidget {
final Future<FirebaseApp> _initialization = Firebase.initializeApp();
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: FutureBuilder(
future: _initialization,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return LoginWrapper();
}
return SplashScreen();
},
),
);
}
}
it shows your SplashScreen while loading your firebase App ;)

Categories

Resources