flutter: substring的使用要小心

最近日子真的過得好苦...
沒錢,錢不夠用.
真希望有人能贊助app設計啊....

好啦,來看問題:

String substring2 = _lastPairMac.substring(0, 7);
出現錯誤:Unhandled Exception: RangeError (end): Invalid value: Only valid value is 0: 7

好可怕,寫程式就常常出現這種沒預想到的錯誤.
正常情況下不會出問題.但....很多時候會出問題是當null時才會出現,被新的user發現...

solution:

在處理這種情況時,你需要確保在呼叫 substring 方法之前檢查字串的長度。你可以使用條件語句來確保字串夠長,然後再呼叫 substring

例如:

_lastPairMac是一個字串. 我們要對字串做處理.
一般來說,我們常省略判斷_lastPairMac的長度,但這樣就容易出現上面的錯誤.
所以...


String substring2 = _lastPairMac.length >= 7 ? _lastPairMac.substring(0, 7) : _lastPairMac;

這樣做會檢查_lastPairMac 的長度是否大於等於7,如果是,則取得子字串,否則就將整個字串賦值給substring2.

確保在使用 substring 或任何涉及索引的字串操作之前進行適當的邊界檢查,以防止出現 RangeError.

---


除此之外,還遇到了電話號碼的問題:

What is maximum and minimum length of any mobile number across the world?

”全球“手機號碼的最大和最小長度是多少?

The minimum length is 4 for Saint Halena (Format: +290 XXXX) and Niue (Format: +683 XXXX). +290 is the country code of Saint Halena and +683 is the country code of Niue. Also both have same International call prefix: 00

The maximum length is 12 for French Guiana, Guadeloupe, Martinique and Reunion having mobile prefix "700". Their mobile length varies (i.e., 9) if the mobile prefix is "6".

French Guiana

Country code : +594

Format : +594 700 XXX XXX XXX

Guadeloupe

Country code : +590

Format : +590 700 XXX XXX XXX

Martinique

Country code : +596

Format : +596 700 XXX XXX XXX

Reunion

Country code : +262

Format : +262 700 XXX XXX XXX

The following link contains the list of different countries, their International calling code, Mobile prefix, National significant number (i.e., the number of digits after the country code excluding any trunk code or access code which is also called as length of the mobile number), and different carriers.


wiki這張表有:

https://en.wikipedia.org/wiki/List_of_mobile_telephone_prefixes_by_country


所以就要設計4-12個digits以應變不同國家地區的電話號碼.

這在flutter中,常常會遇到有使用者的輸入電話欄位之驗證都會用到.




留言

這個網誌中的熱門文章

最爛的銀行服務-玉山銀行

Mark App Design Apps - Terms and Privacy Policy (服務條款,隱私權政策)

SMR疊瓦式hdd致命缺陷被解決????!!!

ios app 上架時app icon要注意事項

更改google drive預設存放目錄位置Change Google Drive Default Folder Location in Windows

google play 正式發布前測試報告...非常好用.

舊有app在Android 12 閃退問題& app Splash screens

app bundle and bundletool. 關於aab安裝問題

關於google play console app應用程式簽署

Google Play badge徽章產生器