make function await flutter - flutter

I have this variable
dynamic _permission = true;
after clicked on button. I need to display sncakbar if _permission= false thats mean user has no permission to access the page else go to page.
but I faced an issue that _permission always equal true.
even if permission return false from api.
here is the code
Future<void> checkPermesssion() async {
String api_token = await getToken();
final response = await http.post(
Uri.parse(PermissionURL),
headers: {'Accept': 'application/json',
'Authorization': 'Bearer $api_token'
},
);
var permission = jsonDecode(response.body)['permission'];
setState(() {
_permission = permission;
});
}
and here is the button code
child: ElevatedButton(
onPressed: () {
checkPermesssion();
_permission ?
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => page()))
:
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
'You don\'t have permession to access this page '),
behavior: SnackBarBehavior.floating,
margin: EdgeInsets.all(50),
elevation: 30,
action: SnackBarAction(
label: 'Dismiss',
disabledTextColor: Colors.white,
textColor: Colors.yellow,
onPressed: () {
ScaffoldMessenger.of(context).hideCurrentSnackBar();
},
),
),
);
},
How can I do that please

Try this for button's code :
child: ElevatedButton(
onPressed: () async{
await checkPermesssion();
_permission ?
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => page()))
:
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
'You don\'t have permession to access this page '),
behavior: SnackBarBehavior.floating,
margin: EdgeInsets.all(50),
elevation: 30,
action: SnackBarAction(
label: 'Dismiss',
disabledTextColor: Colors.white,
textColor: Colors.yellow,
onPressed: () {
ScaffoldMessenger.of(context).hideCurrentSnackBar();
},
),
),
);
},

Related

Bad state: field does not exist within the DocumentSnapshotPlatform problem

I want to do the sign-in method and I face this run time error ,I don't know the reason cause it or how to solve it.
I want to checks all cases for login
my code is:
ElevatedButton(
onPressed: logIn,
child: StreamBuilder<User?>(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot) {
// try{
print('inside bulder method');
if (snapshot.connectionState ==
ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator());
}
if (snapshot.hasData) {
print('have account');
return home();
} else {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: const Text('Invalid email/password'),
backgroundColor: Colors.red.shade400,
margin: const EdgeInsets.fromLTRB(6, 0, 3, 0),
behavior: SnackBarBehavior.floating,
action: SnackBarAction(
label: 'Dismiss',
disabledTextColor: Colors.white,
textColor: Colors.white,
onPressed: () {},
)));
return Text('there is something error');
}
},
),)
and login method:
``Future<void> logIn() async {
print('inside login method');
if (_formKey.currentState!.validate()) {
try {
await FirebaseAuth.instance.signInWithEmailAndPassword(
email: emailController.text.trim(),
password: passwordController.text.trim(),
);
print('end try');
} catch (e) {
if (emailController.text.isNotEmpty &&
passwordController.text.isNotEmpty) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: const Text('Invalid email/password'),
backgroundColor: Colors.red.shade400,
margin: const EdgeInsets.fromLTRB(6, 0, 3, 0),
behavior: SnackBarBehavior.floating,
action: SnackBarAction(
label: 'Dismiss',
disabledTextColor: Colors.white,
textColor: Colors.white,
onPressed: () {},
)));
print("after check");
}
}
}
}
`
`
each textFormField is have the correct controller
and because of this problem I can't run this method correctly

Flutter heroTag tree

what s wrong with my code here?
Every time i press the button it show that i've must using a heroTag or something like that, can someone tell me what's wrong?
MaterialButton(
elevation: 0,
onPressed: () async {
await Future.delayed(const Duration(seconds: 3), () {
Navigator.push(context,
MaterialPageRoute(builder: (_) {
return const CalednarOrtodox();
}));
});
setState(() {
userPost = _textController.text;
});
},
color: const Color.fromRGBO(0, 85, 72, 1),
child: const Text(
"Next",
style: TextStyle(
color: Colors.white,
),
),
)
When i tap on the button this is happening:
here

Flutter ShowDialog not closing

I can't solve this problem. I'm trying to do this step by step. When users push the button, first they gonna see AlertDialog, then the function startFilePickerBig will run. After the user chose files and is done with the startFilePickerBig function AlertDialog must close. But when I add Navigator.pop(context) after "await startFilePickerBig()" , alertdialog not working. When I remove "Navigator.pop(context)" which I wrote under the "await startFilePickerBig()", AlarmDialog works fine. How can I fix this?
OutlinedButton(
style: ButtonStyle(side: MaterialStateProperty.all(const BorderSide(width: 1.0, color: Color(0xFFF38F1D))), shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(7))), foregroundColor: MaterialStateProperty.all(const Color(0xFFF38F1D))),
onPressed: () async {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: const Text(''),
content: const Text('Pease wait, Images loading... '),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text('Close')),],
);
});
await startFilePickerBig();
Navigator.pop(context);
},
child: const Text("Add Image"),
)
What I might do here is to use ProgressIndicator instead of AlertDialogBox with the help of ternary operator on the build function.
However, as per your approach, this might work:
onPressed: () async {
await startFilePickerBig();
bool result= await showDialog(context:context, builder:( BuildContext context){
return AlertDialog(
title:Text("Pease wait, Images loading..."),
actions: [
TextButton(
child: Text("Picked"),
onPressed: (){
Navigator.of(context).pop(true);
},
),
TextButton(
child: Text("Not picked"),
onPressed: (){
Navigator.of(context).pop(false);
},
),
],
);
});
if(result==true){
//Do whatever you want
Fluttertoast.showToast(
msg: 'Items picked',
toastLength: Toast.LENGTH_LONG,
backgroundColor: kPrimaryColor);
removeFromList(item);
}else{
//Your code
}
}

Circular progress indicator not showing in flutter

I am trying to show an CircularProgressIndicator whenever user presses on register button, here is my code:
onPressed: () async{
if (_email.isNotEmpty && _password.isNotEmpty) {
startProgressIndicator();
FirebaseAuth mAuth = FirebaseAuth.instance;
UserCredential credential = await mAuth.createUserWithEmailAndPassword(email: _email, password: _password);
print(credential.user!.email);
//stopProgressIndicator();
} else {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(
"Please enter all information!",
style: TextStyle(
color: Colors.white,
fontSize: 15,
fontWeight: FontWeight.bold
),
),
backgroundColor: Colors.black,
elevation: 5,
duration: Duration(
seconds: 3
),
action: SnackBarAction(
label: "close",
onPressed: (){
ScaffoldMessenger.of(context).hideCurrentSnackBar();
},
),
));
}
startProgressIndicator():
CircularProgressIndicator startProgressIndicator() {
return CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Colors.orange),
backgroundColor: Colors.black,
strokeWidth: 5,
);
}
stopProgressIndicator():
CircularProgressIndicator stopProgressIndicator() {
return CircularProgressIndicator(
value: 0,
);
}
The loading icon doesn't appear at all.
All colors are correct(i.e. background color and progress bar color are different)
What is the issue here?
EDIT: I added the following code but it still isn't working:
Column(
children: [
<Other widgets>
Visibility(
visible: _isProgressVisible,
child: CircularProgressIndicator(),
)
]
)
and I set _isProgressVisible to true and false:
if (_email.isNotEmpty && _password.isNotEmpty) {
setState(() {
_isProgressVisible = true;
});
FirebaseAuth mAuth = FirebaseAuth.instance;
UserCredential credential = await mAuth.createUserWithEmailAndPassword(email: _email, password: _password);
print(credential.user!.email);
setState(() {
_isProgressVisible = false;
});
}
You are not showing the returned widget anywhere, startProgressIndicator() returns the widget but you're just calling not rendering it,
Either use like this
showCupertinoDialog(
useRootNavigator: true,
barrierDismissible: false,
context: context,
builder: (context) {
return startProgressIndicator();
},
);
If you want to show that somewhere else you can do that like this
Container(
margin: const EdgeInsets.all(16),
child: Column(children: [
Visibility(
visible: showIndicator,
child: startProgressIndicator()),
const SizedBox(height: 10),
RaisedButton(
child: const Text('Here'),
onPressed: () => setState(() => showIndicator = !showIndicator),
)
]),
);
return startProgressIndicator();
That's just simple mistake
You have to return widget;

How to share Flutter_App_link to social media like facebook, twitter, instagram?

I just want to share my app link to social media like facebook, twitter, Instagram but currently just wanna share simple text on social media.
here, what I have tried:
I used social_share_plugin package but getting an Exception on compile time.
code for facebook
IconButton(
icon:Image.asset("assets/icons/facebook_logo1.png",fit:BoxFit.contain,color: Colors.white,),
onPressed: ()async{
String faceString="Sharing My App";
await SocialSharePlugin.shareToFeedFacebook('caption', faceString);
},
),
for instagram
IconButton(
icon:Image.asset("assets/icons/instagram_logo1.png",fit:BoxFit.contain,color: Colors.white,),
onPressed: ()async{
String instaString="Sharing My App";
await SocialSharePlugin.shareToFeedInstagram('caption', instaString);
},
)
You can use this plugin https://pub.dev/packages/flutter_social_content_share
/// SHARE ON FACEBOOK CALL
shareOnFacebook() async {
String result = await FlutterSocialContentShare.share(
type: ShareType.facebookWithoutImage,
url: "https://www.apple.com",
quote: "captions");
print(result);
}
/// SHARE ON INSTAGRAM CALL
shareOnInstagram() async {
String result = await FlutterSocialContentShare.share(
type: ShareType.instagramWithImageUrl,
imageUrl:
"https://post.healthline.com/wp-content/uploads/2020/09/healthy-eating-ingredients-732x549-thumbnail-732x549.jpg");
print(result);
}
/// SHARE ON WHATSAPP CALL
shareWatsapp() async {
String result = await FlutterSocialContentShare.shareOnWhatsapp(
number: "xxxxxx", text: "Text appears here");
print(result);
}
/// SHARE ON EMAIL CALL
shareEmail() async {
String result = await FlutterSocialContentShare.shareOnEmail(
recipients: ["xxxx.xxx#gmail.com"],
subject: "Subject appears here",
body: "Body appears here",
isHTML: true); //default isHTML: False
print(result);
}
/// SHARE ON SMS CALL
shareSMS() async {
String result = await FlutterSocialContentShare.shareOnSMS(
recipients: ["xxxxxx"], text: "Text appears here");
print(result);
}
///Build Context
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Column(
children: <Widget>[
Text('Running on: $_platformVersion\n'),
RaisedButton(
child: Text("Share to facebook button"),
color: Colors.red,
onPressed: () {
shareOnFacebook();
},
),
RaisedButton(
child: Text("Share to instagram button"),
color: Colors.red,
onPressed: () {
shareOnInstagram();
},
),
RaisedButton(
child: Text("Share to whatsapp button"),
color: Colors.red,
onPressed: () {
shareWatsapp();
},
),
RaisedButton(
child: Text("Share to email button"),
color: Colors.red,
onPressed: () {
shareEmail();
},
),
RaisedButton(
child: Text("Share to sms button"),
color: Colors.red,
onPressed: () {
shareSMS();
},
),
],
),
),
);
}
you can use the share plugin
and then here is how you share your data
import 'package:share/share.dart';
IconButton(
icon:Image.asset("assets/icons/facebook_logo1.png",fit:BoxFit.contain,color: Colors.white,),
onPressed: (){
Share.share('check out my website https://example.com');
}
`),