Launch link in flutter - flutter

i would like to launch custom dynamic links..
i have getter which load string text from database, this string text is user input with them IG username
bio is IG username, exsample #instagram
String getBio(String bio) {
if (widget.isMyProfile) {
return bio;
} else if (bio == "") {
return "";
} else {
return bio;
}
}
i want to have static link "**https://instagram.com/**;" where end of link will be dynamic instagram user name
example: 'https://instagram.com/instagram';
_launchURLIG() async {
const url = 'https://instagram.com/';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
=====
something like this. https://instagram.com' + getBio
_launchURLIG() async {
const url = 'https://instagram.com' + getBio ;
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}

You should past profile as a parameter to your function
_launchURLIG(String userId) async {
String url = 'https://instagram.com/' + userId ;
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}

Maybe you need this package to run link:
https://pub.dev/packages/url_launcher

Related

Flutter || url_launcher failed to open specified url

I'm trying to launch this URL ("https://m.me/nagadhat"). but cannot launch on my app. But I can visit this URL from my browser and anywhere else.
String chatURL = "https://m.me/nagadhat";
var url = Uri.parse(chatURL);
if (await canLaunchUrl(url)) {
await launchUrl(url);
} else {
throw 'Could not launch $url';
}
This is the screenshot when I'm triggering the code
Adding LaunchMode to launchUrl solved my issue.
This is the changed code.
String chatURL = "https://m.me/nagadhat";
var url = Uri.parse(chatURL);
if (await canLaunchUrl(url)) {
await launchUrl(url, mode: LaunchMode.externalApplication);
} else {
throw 'Could not launch $url';
}

Flutter Firebase web authentication setup issue

Description:
Trying to setup firebase authentication for web. Please guide how to implement and the steps needed for it. Or if there is some tutorial that explain it well. Need to way to implement authencication for web version only. Any help would be appreciated alot.
Here is I tried but not working for auth and getx. Thank you.
Future<void> checkLoginAndRediect() async {
Authentication authentication = Authentication();
final UserController userController = Get.find(tag: 'userController');
await authentication.autoLogin();
if (userController.previouslyLoggedIn) {
Get.offAll(
const Home(),
);
} else {
Get.offAll(
const SignupPage(),
);
}
Future<bool> init() async {
if (userID.isNotEmpty) {
userController.userID = userID;
var document = await FirebaseFirestore.instance
.collection('users')
.doc(userID)
.get();
if (document.exists) {
//updaiting user data locally from firebase
userController.setUser(
userID,
document.data()!['name'],
document.data()!['phone'],
document.data()!['email'],
document.data()!['username'],
document.data()!['profilePictureLink'] ??
"https://firebasestorage.googleapis.com/v0/b/matab-a53a8.appspot.com/o/DefaultProfile.png?alt=media&token=716eca5e-b939-4dfa-8e8e-72b0efc75f7f", //there is always a default profile picture but for those user which are reqistered earlier it will replace their as soon as they sign in, with default dummy pic
);
//fetching user's addresss from firebase
addressDatabaseService
.getAddress(userID)
.then((value) {})
.catchError((error) {
return false;
});
//fetching bank details here
var bankDetails =
FirebaseFirestore.instance.collection('bankDetails').doc("1").get();
bankDetails.then((value) {
transactionController.setBankDetails(
value.data()!['bankName'],
value.data()!['accountNumber'],
value.data()!['accountTitle'],
value.data()!['bankBranch']);
orderController.userID = userID;
}).catchError((error) {
debugPrint(error.toString());
});
//fetching user optional details from firebase if already exists there
optionalProfileDetailsController.getProfileDetails(
userID); //this will fetch and store user optional details in controller, controller calls database service itself to fetch data from database
userController.previouslyLoggedIn =
true; //updating user already exists flag to true
}
return true;
} else {
return false;
}
}
Future<void> autoLogin() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
bool userStatus = prefs.containsKey('uid');
if (userStatus) {
String? uid = prefs.getString('uid');
userID = uid!;
userController.userID = userID;
await init();
userController.previouslyLoggedIn = true;
} else {
userController.previouslyLoggedIn =
false; //if this is false then in main.dart=>checkLoginAndRediect we will check for this and redirect user to signup page
debugPrint("not connected");
}
}
login(String identifier, String password) async {
String errorMessage;
final auth = FirebaseAuth.instance;
try {
final UserCredential userCredential = await auth
.signInWithEmailAndPassword(email: identifier, password: password);
final User? user = userCredential.user;
if (user != null) {
if (!user.emailVerified) {
Get.snackbar(" Email not Verified ", "Please verify your email.",
colorText: whiteColor,
backgroundColor: Colors.red,
duration: const Duration(seconds: 5),
snackPosition: SnackPosition.BOTTOM);
return;
} else {
userID = user.uid;
userController.userID = userID;
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('uid', userCredential.user!.uid);
await init();
Get.offAll(() => const Home());
}
}
} on FirebaseAuthException catch (error) {
switch (error.code) {
case "user-not-found":
errorMessage = "Incorrect Email or Password".tr;
break;
case "wrong-password":
errorMessage = "Incorrect Password".tr;
break;
case "invalid-email":
errorMessage = "Email is not valid.".tr;
break;
default:
errorMessage = "Something Went Wrong,";
}
Get.snackbar(errorMessage, "Please Try Again".tr,
snackPosition: SnackPosition.BOTTOM, backgroundColor: Colors.red);
}
}
signUp(String name, String phone, int usercnic, String email, String password,
String confirmPassword) async {
//below is a default image link, it will be replaced by user's profile picture when he/she sign up for the first time later on he can updateq his/her profile picture
String profilePictureLink =
"https://firebasestorage.googleapis.com/v0/b/matab-a53a8.appspot.com/o/DefaultProfile.png?alt=media&token=716eca5e-b939-4dfa-8e8e-72b0efc75f7f";
final auth = FirebaseAuth.instance;
String errorMessage;
if (confirmPassword != password) {
generateError("Incorrect Confirm password".tr, "Please try again".tr);
return;
}
try {
final UserCredential signUPResponse =
await auth.createUserWithEmailAndPassword(
email: email,
password: password,
);
User? user = signUPResponse.user;
if (user != null) {
userDBService.addUser(
user.uid, name, phone, email, usercnic, profilePictureLink);
userController.setUser(
user.uid, name, phone, email, usercnic, profilePictureLink);
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('uid', user.uid);
await user.sendEmailVerification();
Get.snackbar(
"Email Verification",
"Please verify your email",
snackPosition: SnackPosition.BOTTOM,
);
var bankDetails =
FirebaseFirestore.instance.collection('bankDetails').doc("1").get();
bankDetails.then((value) {
transactionController.setBankDetails(
value.data()!['bankName'],
value.data()!['accountNumber'],
value.data()!['accountTitle'],
value.data()!['bankBranch']);
}).catchError((error) {
throw (error);
});
}
Get.offAll(() => const LoginPage());
} on FirebaseAuthException catch (error) {
switch (error.code) {
case "user-not-found":
errorMessage = "Incorrect Email or Password";
break;
case "wrong-password":
errorMessage = "Incorrect Password";
break;
case "email-already-in-use":
errorMessage = "Email already in use";
break;
case "invalid-email":
errorMessage = "Email is not valid.";
break;
case "weak-password":
errorMessage = "Password should be at least 6 characters ";
break;
default:
errorMessage = error.code;
}
// Get.snackbar(errorMessage.tr, "Please Try Again.".tr,
// snackPosition: SnackPosition.BOTTOM);
generateError(errorMessage.tr, "Please Try Again.".tr);
}
}
You need to start by adding the lib
flutter pub add firebase_auth
then you need to make sure you installed firebase core and it's working from your app to firebase,
flutter pub add firebase_core
to init your firebase app, start by setting the options
class DefaultFirebaseOptions {
static FirebaseOptions get currentPlatform {
if (kIsWeb) {
return web;
}
switch (defaultTargetPlatform) {
case TargetPlatform.android:
return android;
case TargetPlatform.iOS:
return ios;
case TargetPlatform.macOS:
return macos;
case TargetPlatform.windows:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for windows - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
case TargetPlatform.linux:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for linux - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
default:
throw UnsupportedError(
'DefaultFirebaseOptions are not supported for this platform.',
);
}
}
static const FirebaseOptions web = FirebaseOptions(
apiKey: ,
appId: ,
messagingSenderId: ,
projectId: ,
authDomain: ,
storageBucket: ,
measurementId: ,
);
and the initialization of your app
switch (defaultTargetPlatform) {
case TargetPlatform.windows:
_app = await desktop.Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
break;
default:
_app = await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform);
}
await Firebase.initializeApp();
and todo simple log in try
try {
final credential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: emailAddress,
password: password,
);
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
print('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
print('The account already exists for that email.');
}
} catch (e) {
print(e);
}
for more info please follow:
https://pub.dev/packages/fireflutter

How can i pass username and password int http req

Recently I have to make login to ubnt(UNifi) devices from flutter application
so I must pass user and password into URL
this is my code :
const url = 'http://10.66.5.8/login.cgi?uri=/';
var res = await http.post(Uri.parse(url), body: {
'username': 'ubnt',
'password': 's11n',
});
if (res.statusCode == 200) {
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
} else {
print(res.statusCode);
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('Error')));
}
I try with API HTTP but no result

How to launch other android apps using the flutter app

I have used the following method as specified in the documentation.
Future<void> launchUniversalLink(String url) async {
if (await canLaunch(url)) {
final bool nativeAppLaunchSuccess = await launch(url, forceSafariVC: false, universalLinksOnly: true);
print(nativeAppLaunchSuccess);
}else {
print('launch not successfull');
}
}
if I give URL = 'https://www.WhatsApp.com'
print(nativeAppLaunchSuccess); output ==> true
but still the app launches in the browser.
can anyone help me with this problem
Oh I'm sorry. This is my mistake.
Please use 'device_apps' flutter package and usage is below.
And here is a how to know app package name.
https://www.techmesto.com/find-android-app-package-name/
In ios, you know other app's custom Url schema that officially opened.
But usually we can not know that url.
So below ios code is executed, it will open appstore page and need to push 'open' button.
if (Platform.isAndroid) {
if (await DeviceApps.isAppInstalled('com.nbt.moves') ==
true) {
DeviceApps.openApp('com.nbt.moves');
}
} else {
const url =
'https://apps.apple.com/kr/app/%EC%BA%90%EC%8B%9C%EC%8A%AC%EB%9D%BC%EC%9D%B4%EB%93%9C-%EC%8A%A4%ED%85%9D%EC%97%85/id1400703652?uo=4';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}

Url launcher exception in iOS when subject OR body is in Chinese language

Below code working in android device but in iOS device it's throw an exception
dynamic _sendEmail() async {
String url = 'mailto:support#test.com?subject=请写以上这个线';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
Could not launch mailto:support#k8sllc.com?subject=请写以上这个线
You should encode your url:
String url = Uri.encodeComponent('mailto:support#test.com?subject=请写以上这个线');
so it looks like this:
mailto%3Asupport%40test.com%3Fsubject%3D%E8%AF%B7%E5%86%99%E4%BB%A5%E4%B8%8A%E8%BF%99%E4%B8%AA%E7%BA%BF