【问题标题】:Flutter change string if condition如果条件颤动更改字符串
【发布时间】:2021-05-24 14:39:29
【问题描述】:

我正在打开带有文本和数字的whatsapp url。

问题是我有两种号码

+923323789222 & 03323789222

Whatsapp 不是从 0 开始的开放号码,所以我需要做的是如果号码有 0 将其替换为 +92

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

在电话中,当我通过 +92 时它工作正常,所以我的问题是,如果我的号码以 0 开头并替换为 +92,我该如何替换

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您可以检查您的号码是否以 0 开头,只需替换为 +92,如果它不以 0 开头,则保持不变。

                    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);
    

    【讨论】:

      【解决方案2】:

      只需使用以下代码替换特定字符串。

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

      您也可以使用regex 进行字符串替换。

      【讨论】:

        【解决方案3】:

        试试这个:

        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');
        }
        

        用法:

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

        【讨论】:

          猜你喜欢
          • 2018-11-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-11-05
          • 2013-05-12
          • 1970-01-01
          • 2013-09-20
          • 1970-01-01
          相关资源
          最近更新 更多