fix net::err_unknown_url_scheme whatsapp link on flutter webview - android

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 (+).

Related

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 navigate screen in main page on flutter?

i want wait 5 seconds on main page and display loading animation then navigate to another page.
here is my code
import 'mainPage.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'dart:async';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool isLoading = true;
#override
void initState() {
super.initState();
loadData();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Colors.cyan,
body: Builder(
builder: (context) => Center(
child: Container(
child: SpinKitCubeGrid(color: Colors.white, size: 50.0),
),
),
),
),
);
}
Future loadData() async {
return new Timer(Duration(seconds: 5), () {
setState(() {
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => MainPage()));
});
});
}
}
but i got this error:
Unhandled Exception: Navigator operation requested with a context that does not include a Navigator.
what should i do?
Wrap MyApp with MaterialApp which will provide the right context to Navigator
void main() {
runApp(MaterialApp(home: MyApp()));
}
Maybe this will help U
static Route route() {
return MaterialPageRoute<void>(builder: (_) => MyApp());
}
onPressed: () => Navigator.of(context).push<void>(MainPage.route()),
................
static Route route() {
return MaterialPageRoute<void>(builder: (_) => MainPage());
}
onPressed: () => Navigator.of(context).push<void>(MyApp.route()),
Can you try it like this? I didn't run the code but showing the basic idea. Just pass the context and call it from build function.
class _MyAppState extends State<MyApp> {
bool isLoading = true;
#override
Widget build(BuildContext context) {
loadData(context);
return MaterialApp(
...
);
}
Future loadData(context) async {
...
}
}
You need a context to navigate with the Navigator.
To navigate without using context you can use a package called GetX
Example:
Add "Get" before your MaterialApp, turning it into GetMaterialApp
GetMaterialApp( // Before: MaterialApp(
home: MyHome(),
)
Navigate to a new screen:
Get.to(NextScreen());

i am facing flutter webview issue

I am new in a flutter. I m facing an issue in flutter_webview here is my code IDK what's wrong with it. I write this code with the help of StackOverflow and an official plugin. my HTML files working fine
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:webview_flutter/webview_flutter.dart';
class Licences extends StatefulWidget {
#override
_LicencesState createState() => _LicencesState();
}
class _LicencesState extends State<Licences> {
WebViewController webViewController;
String filePath = 'files/PrivacyPolicy.html';
loadHtml() async {
String data = await rootBundle.loadString(filePath);
webViewController.loadUrl(Uri.dataFromString(data,
mimeType: 'text/html', encoding: Encoding.getByName('utf-8'))
.toString());
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Open-Source Licences'),
),
body: Builder(builder: (BuildContext context) {
return WebView(
initialUrl: '',
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController controller) {
webViewController = controller;
loadHtml();
},
);
}),
);
}
}

Firebase Asking to initialize app even though it has already been initialized

I created this test file to check for available firebase users and then move to the appropriate screen according to the response. Although I have initialized the app, it still show the error that no Firebase DEFAULT APP HAS BEEN CREATED. Call Firebase.initializeApp. Am i doing something wrong here? Also if there is any other way to check for the user being logged in or not then please tell. Keep in mind I need to fetch the data from firestore too before showing MainView().
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:splashscreen/splashscreen.dart';
import 'MainPages/LoginScreen.dart';
import 'MainPages/MainView.dart';
import 'Services/User.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
Firebase.initializeApp();
runApp(
new MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.deepOrange,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
builder: EasyLoading.init(),
home: new MyApp(),
),
);
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
Future<Widget> loadFromFuture() async {
if (FirebaseAuth.instance.currentUser != null) {
DocumentSnapshot doc = await FirebaseFirestore.instance
.collection("users")
.doc(FirebaseAuth.instance.currentUser.uid)
.get();
currentUser = MyUser.fromDocument(doc);
return Future.value(new MainView());
} else {
return Future.value(new LoginScreen());
}
}
#override
Widget build(BuildContext context) {
return new SplashScreen(
navigateAfterFuture: loadFromFuture(),
title: new Text(
'Welcome In SplashScreen',
style: new TextStyle(fontWeight: FontWeight.bold, fontSize: 20.0),
),
image: new Image.network('https://i.imgur.com/TyCSG9A.png'),
backgroundColor: Colors.white,
styleTextUnderTheLoader: new TextStyle(),
photoSize: 100.0,
onClick: () => print("Flutter Egypt"),
loaderColor: Colors.red);
}
}
You need to await for firebase to be initialized
Please refer below code
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
runApp(MyApp());
}

Flutter get source URL along with Text shared from web page

I am new to Flutter. I want to get the text along with its source. Currently, I am using receive_sharing_intent which is serving the purpose of TextStream and Url individually.
I want to share the copied text from the browser and keep its URL along with it.
I followed this doc hence my main.dart is same as:
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:receive_sharing_intent/receive_sharing_intent.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
StreamSubscription _intentDataStreamSubscription;
List<SharedMediaFile> _sharedFiles;
String _sharedText;
#override
void initState() {
super.initState();
// For sharing or opening urls/text coming from outside the app while the app is in the memory
_intentDataStreamSubscription =
ReceiveSharingIntent.getTextStream().listen((String value) {
setState(() {
_sharedText = value;
});
}, onError: (err) {
print("getLinkStream error: $err");
});
// For sharing or opening urls/text coming from outside the app while the app is closed
ReceiveSharingIntent.getInitialText().then((String value) {
setState(() {
_sharedText = value;
});
});
}
#override
void dispose() {
_intentDataStreamSubscription.cancel();
super.dispose();
}
#override
Widget build(BuildContext context) {
const textStyleBold = const TextStyle(fontWeight: FontWeight.bold);
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: Column(
children: <Widget>[
Text("Shared files:", style: textStyleBold),
Text(_sharedFiles?.map((f)=> f.path)?.join(",") ?? ""),
SizedBox(height: 100),
Text("Shared urls/text:", style: textStyleBold),
Text(_sharedText ?? "")
],
),
),
),
);
}
}
Any suggestions on how to proceed to this or any Reference will work.
Thanks!!

Categories

Resources