rameez khan
rameez khan

Reputation: 359

Flutter change string if condition

I am opening whatsapp url with text and number.

Issue is i have 2 types of number

+923323789222 & 03323789222

Whatsapp is not opening number starting from 0 so what i need to do is if number have 0 replace it with +92

    var url ='whatsapp://send?phone=+923323789222&text=Apna ${widget.data['selererName']} ko ${Ggive.toString()} Rupees dene hein';

in phone when i am passing with +92 its working fine so my question is how can i replace if my number start with 0 and replace with +92

Upvotes: 0

Views: 781

Answers (3)

Jigar
Jigar

Reputation: 3281

Just use the below code to replace a particular string.

var url ='whatsapp://send?phone=+923323789222&text=Apna ${widget.data['selererName']} ko ${Ggive.toString()} Rupees dene hein';

url.replaceAll('phone=0', 'phone=+92');

You can also use regex for string replacement.

Upvotes: 1

Andrej
Andrej

Reputation: 3235

Try this:

String formatPhoneNumber(String phoneNumber) {
 if (phoneNumber.length < 1) return '';
 
 // if the phone number doesn't start with 0,
 // it is already formatted and we return in the
 // way it is.
 if (phoneNumber[0]  != '0') return phoneNumber;
 
 // if it starts with 0 then we replace the 0 with +92
 // and return the new value.
 return phoneNumber.replaceFirst(RegExp('0'), '+92');
}

Usage:

print(formatPhoneNumber('+923323789222'));
// OUTPUT: +923323789222

print(formatPhoneNumber('03323789222'));
// OUTPUT: +923323789222

Upvotes: 0

Umaiz Khan
Umaiz Khan

Reputation: 1227

You can just check if your number have 0 in start just replace with +92 and if its not start with 0 then remain it same.

                String num = yournumber.toString();
                if(num[0] == "0"){
                  print('have zero');
                   String numb2 = num.substring(0, 0) + "+92" + num.substring(1);
                   print(numb2);
                   num = numb2;
                }
                var url ='whatsapp://send?phone=${num}&text=Apna ${widget.data['selererName']} ko ${Ggive.toString()} Rupees dene hein';
                print(url);

Upvotes: 2

Related Questions