I'm building a VPN application with flutter. After users write their server, username, and password they used to click the 'connect' button. But for now, I have two buttons that contain connect and disconnect functions.
connect function:
ElevatedButton(
child: const Text('Connect'),
onPressed: () => FlutterVpn.connectIkev2EAP(
server: _addressController.text,
username: _usernameController.text,
password: _passwordController.text,
),
),
disconnect function:
ElevatedButton(
child: const Text('Disconnect'),
onPressed: () => FlutterVpn.disconnect(),
),
My question is, how to combine those 2 functions above become one button? Thank you in advance for any help.
I've tried this, but it throws me an error.
ElevatedButton(
onPressed: () async{
if (state == FlutterVpnState.disconnected){
child: Text('Connect'),
FlutterVpn.connectIkev2EAP(
server: _addressController.text,
username: _usernameController.text,
password: _passwordController.text,
);
}else{
child: const Text('Disconnect')
onPressed: () => FlutterVpn.disconnect();
}
}
),
You can do it use ternary expression like checkUp? if true:else for text and if-else conditional statement will work fine and looks better on onPressed.
ElevatedButton(
onPressed: () async{
if (state == FlutterVpnState.disconnected){
FlutterVpn.connectIkev2EAP(
server: _addressController.text,
username: _usernameController.text,
password: _passwordController.text,
);
}else{
FlutterVpn.disconnect();
}
},
child: Text(state == FlutterVpnState.disconnected?'Connect':'Disconnect'),
),
I will recommend you to check conditional-expressions
You can conditionally set the value of Text this way:
Text(state == FlutterVpnState.disconnected ? 'Connect' : 'Disconnect'),
Related
I am trying to log in through my phone number and OTP using firebase and I am using the IntlPhoneField package to enter the number and select desired country code.
Here is how I am doing it
IntlPhoneField(
controller: phoneController,
showCountryFlag: false,
decoration: InputDecoration(
isDense: true,
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: AppColors.greyColor),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: AppColors.greyColor),
),
),
initialCountryCode: 'PK',
onChanged: (phone) {
setState(() {
dialCodeDigit = phone.countryCode;
});
},
)
And i am sending this code and phone number to provider like that
if (_formKey.currentState!.validate()){
AddNewDialogBox.dialog(context, true);
context
.read<LoginPhoneProvider>()
.phoneSignInn(context, phoneController.text, dialCodeDigit);
print(dialCodeDigit);
}
here is my code for getting OTP using provider state management and getting phone number and country code from login screen
Future<void> phoneSignInn(
BuildContext context,
String phoneNumber,
String countryCode,
// String countryCOde,
) async {
TextEditingController codeController = TextEditingController();
if (kIsWeb) {
// !!! Works only on web !!!
ConfirmationResult result =
await _auth.signInWithPhoneNumber(phoneNumber);
// Diplay Dialog Box To accept OTP
showOTPDialog(
phoneNumber: phoneNumber + countryCode,
//countryCode: countryCode,
codeController: codeController,
context: context,
onPressed: () async {
PhoneAuthCredential credential = PhoneAuthProvider.credential(
verificationId: result.verificationId,
smsCode: codeController.text.trim(),
);
await _auth.signInWithCredential(credential);
Navigator.of(context).pop(); // Remove the dialog box
},
);
} else {
// FOR ANDROID, IOS
await _auth.verifyPhoneNumber(
phoneNumber: phoneNumber + countryCode,
// Automatic handling of the SMS code
verificationCompleted: (PhoneAuthCredential credential) async {
// !!! works only on android !!!
await _auth.signInWithCredential(credential);
},
// Displays a message when verification fails
verificationFailed: (e) {
showSnackBar(context, e.message!);
},
// Displays a dialog box when OTP is sent
codeSent: ((String verificationId, int? resendToken) async {
showOTPDialog(
phoneNumber: phoneNumber + countryCode,
// countryCode: countryCode,
codeController: codeController,
context: context,
onPressed: () async {
PhoneAuthCredential credential = PhoneAuthProvider.credential(
verificationId: verificationId,
smsCode: codeController.text.trim(),
);
// !!! Works only on Android, iOS !!!
await _auth.signInWithCredential(credential);
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => const DriverSginUpScreen()));
// Navigator.of(context).pop(); // Remove the dialog box
},
);
}),
codeAutoRetrievalTimeout: (String verificationId) {
// Auto-resolution timed out...
},
);
}
}
incase if you need to know about the dialog that I show after receiving OTP here is the code of OTP dialog
void showOTPDialog({
required BuildContext context,
required TextEditingController codeController,
required VoidCallback onPressed,
required String phoneNumber,
}) {
showDialog(
context: context,
barrierDismissible: false,
builder: (context) => SizedBox(
width: double.infinity,
child: AlertDialog(
title: Text("Enter 6 Digit OTP send to\n$phoneNumber"),
content: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
PinCodeTextField(
pinTheme: PinTheme(
shape: PinCodeFieldShape.box,
borderRadius: BorderRadius.circular(5),
fieldHeight: 60,
fieldWidth: 30,
activeFillColor:
Colors.white,
),
appContext: context,
length: 6,
controller: codeController,
onChanged: (value) {
print(value);
}
),
],
),
actions: <Widget>[
TextButton(
onPressed: onPressed,
child: const Text("Done"),
)
],
),
),
);
}
But I am getting an error related to phone format I don't know what I am doing wrong and how to resolve it here is an error that I receive after entering the phone number:
The format of the phone number provided is incorrent
Please enter the phone number in a format that can
parsed into E.164 format. E.164 phone numbers are
written in the format [+|country code][subscriber
number Including area codel. Invalid format. 1
I have a SwitchListTile in my App that determine the text that should be written on another button based on its value. Everything is working fine except for one thing which is that the first time you open the app, the initial text on the button will be nothing '' just as it was declared first time until I switch the SwitchListTile for the first time. So I want to know how to make the text appear from the moment you enter this page.
This is my code:
static String buttonText='';
SwitchListTile(
title: const Text('Enable Bluetooth'),
value: _bluetoothState.isEnabled,
onChanged: (bool value) {
// Do the request and update with the true value then
future() async {
// async lambda seems to not working
if (value) {
await FlutterBluetoothSerial.instance.requestEnable();
setState(() {buttonText = "Press to start collection" ; });
} else {
await FlutterBluetoothSerial.instance.requestDisable();
setState(() {buttonText = "Please enable bluetooth in your device" ; });
}
}
future().then((_) {
setState(() {});
});
},
),
.......................
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.red,
padding: const EdgeInsets.symmetric(horizontal: 30, vertical:40),
textStyle:
const TextStyle(fontSize: 30, fontWeight: FontWeight.bold)),
onPressed: () {
if(_bluetoothState.isEnabled){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const BluetoothConnectionTask()),
);
}
},
child: Text(
buttonText,
style: TextStyle(fontSize: 28,color: Colors.black, letterSpacing: 2.0),
),
),
Please update the Text widget set in your elevated button as below.
Text(
_bluetoothState.isEnabled ? "Press to start collection" : "Please enable bluetooth in your device",
style: TextStyle(fontSize: 28,color: Colors.black, letterSpacing: 2.0),
)
And remove
setState(() {buttonText = "Press to start collection" ; });
setState(() {buttonText = "Please enable bluetooth in your device" ; });
from the onChanged method.
It is not working from first time because, onChanged method will get call when you interact with the SwitchListTile.
If still it's not working, Please let me know with the issue.
I am working on a login system, where i authenticate user by OTP ,Here i want to disable the Resend OTP button for 30 seconds every time the user clicks it and show the time remaining
if you want to have a live counter for showing the user the seconds past you should use stream builder
StreamBuilder(
stream: _timerStream.stream,
builder: (BuildContext ctx,
AsyncSnapshot snapshot) {
return SizedBox(
width: 300,
height: 30,
child:RaisedButton(
textColor: Theme.of(context)
.accentColor,
child: Center(
child:
snapshot.data == 0 ?
Text('send code again')
: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(' button will be enable after ${snapshot.hasData ? snapshot.data.toString() : 30} seconds '),
],)
),
onPressed: snapshot.data == 0 ? () {
// your sending code method
_timerStream.sink.add(30);
activeCounter();
} : null,
)
);
},
)
you can find complete code on dartpad.dev with this link
Declare boolean onPressedValue variable with true,
Add Condition in onPressed Parameter.
bool onPressedValue=true;
RaisedButton(
child: Text('OTP'),
onPressed: onPressedValue==true?(){
setState((){
onPressedValue=false;
});
Timer(Duration(seconds: 30),(){
setState((){
onPressedValue=true;
});
});
}:null)
You can try this
Declare a variable call like this globally
bool shouldButtonEnabled=true;
then on click of send OTP button call this method while you other stuff like sending OTP call this method after it
_disabledButton(){
shouldButtonEnabled=false;
Timer(
Duration(seconds: 30),
() => shouldButtonEnabled=true);
}
and when check this bool on resend OTP button like this
onPressed: () {
if(shouldButtonEnabled){
//do your work here
}
}
I have a FLUTTER problem that I couldn't solve.
Scenario:
1. Implement a QR reader application.
2. The app, read the QR code
3. When you read the QR code, you redirect me to a user's detail page
Problem:
I want to edit that person's data, that's why place a TexFormField, valid fields, but when I call
FUTURE function to send the parameters by post, transforming the body in a JSON so that my server detects it, the button DOES NOTHING.
This is My code
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child : Text("Escanea el codigo QR ", style: TextStyle(fontSize: 25.0),)
),
),
floatingActionButton: FloatingActionButton(
onPressed: obtenerValorQR,
child: Icon(Icons.settings_overscan,),
backgroundColor:Color(0xFF56AB2F)
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
);
}
---------------------------LOGIC -------------------------
Future obtenerValorQR()
async{
_scantemp= await FlutterBarcodeScanner.scanBarcode("#004297", "salir", true);
setState(() {
value=_scantemp;
});
if (value == null) {
Navigator.pushNamed(context, QrPageRoute);
} else {
Navigator.pushNamed(context, HomePageRoute, arguments: value);
}
}
2. App read QR code
Widget _infoPerfilUsuario(BuildContext context , index ){
return Container(
height: 120.0,
child: Card(
child: Padding(
padding: const EdgeInsets.all(15.0),
child: ListTile(
leading: CircleAvatar(backgroundImage:
NetworkImage(widget.usuarios[index].urlFoto), radius: 30.0,),
title: Text("Nombre: ${widget.usuarios[index].nombres}"),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text("Apellidos: ${widget.usuarios[index].apellidos}"),
Text("Zona: ${widget.usuarios[index].territorio}")
],
),
),
)
),
);
}
QR DETAIL
4. I WANT TO OTHER PARAMETERS IN DETAILPAGE FOR EXAMPLE " PESO" BUT TH RAISED BUTTON DONT COMPILE THE CODE
Code where I send the "peso" parameter that I implement, but does not do what I am looking for.
widget _botonesAcciones(BuildContext context , int index ){
return Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
RaisedButton(child: Text("SAVE "), color: Colors.green,
onPressed: () {
final form = formKey.currentState;
if(form.validate()) {
_sendData( context , index );
Navigator.pushNamed(context, QrPageRoute);
}
}
),
],
);
}
I IMPLEMENT THIS FUNCTION IF THE FIELD IS VALIDATED, I just want the data to be sent, I don't want the response body returned, just send the data to my DataBase
Future <void> _sendData (BuildContext context , int index ) async {
final url = Uri.https( _url,'/searchdata.php');
await http.post(url,
body: json.encode({
"id" : "${widget.usuarios[index].idUsuarioMobile}",
"peso" : peso
}),
);
}
Something is wrong?
I think my mistake is in the sendData () function
Hi the solucion is simple:
void _sendData(BuildContext context , int index ) {
var url = Uri.https( _url,'/updatePuntos.php');
http.post(url,
body: json.encode({
"id" : "${widget.usuarios[index].idUsuarioMobile}",
"peso" : peso
}),
);
Looking for me econtre, the answer to my question, was something as simple as returning a void method and sending the data to the server. You should use,
body: json.encode
it will make your life easier.
when i click the fab theres nothin happen
here's my code maybe one of you guys can help :)
void initSpeechRecognizer(){
_speechRecognition = SpeechRecognition
FloatingActionButton(
child: Icon(Icons.mic),
onPressed: (){
if(_isAvailable && !_isListening) _speechRecognition.listen(locale: "id_ID").then((result) => print('result : $result'));
},
heroTag: "mic",
),
Can you try this;
void initSpeechRecognizer(){
_speechRecognition = SpeechRecognition
FloatingActionButton(
child: Icon(Icons.mic),
onPressed: () async {
if(_isAvailable && !_isListening){
var result = await _speechRecognition.listen(locale: "id_ID");
print('result : $result');
}
},
heroTag: "mic",
),