Flutter 使用問題

1.在使用Textfield中遇到的問題

flutter中的onchange方法和oc中的textField:(UITextField *)textField shouldChangeCharactersInRange:方法的不同
onchange方法中調用刷新方法的時候,會導致循環(huán)進入方法中,光標亂閃

///對當前的TextField下的controller監(jiān)聽去刷視圖
_controller.addListener(() {
      setState(() {});
    });


TextField(
                    controller: _controller,
                    focusNode: _focusNode,
                    textInputAction: TextInputAction.search,
                    style: TextStyle(fontSize: 17, color: Colours.text),
                    maxLines: 1,
                    cursorColor: Colours.app_main,
                    textCapitalization: TextCapitalization.characters,
                    inputFormatters: [
                      LengthLimitingTextInputFormatter(21),
                      FilteringTextInputFormatter.allow(RegExp('[a-z0-9A-Z ]')),
                    ],
                    decoration: InputDecoration(
                        border: InputBorder.none,
                        hintText: '請輸入VIN碼或點擊圖片上傳',
                      ///這個右側一鍵清除的按鈕,不隨著文字是否存在變動
                        suffixIcon: _controller.text.isNotEmpty
                            ? IconButton(
                                icon: Icon(IconFont.guanbi,
                                    size: 15, color: Color(0x66000000)),
                                onPressed: () => _controller.clear())
                            : null),
                    onChanged: (value) {
                      ///這邊onchangge的方法,和oc中的輸入監(jiān)聽不同,oc中的監(jiān)聽是實時監(jiān)聽,輸入前,這個是后
                      var formateValue = _viewModel.getFormateVinCode(value);

                      if (formateValue.length % 4 == 0) {
                        var _newtext = _controller.text + ' ';

                        _controller.value = TextEditingValue(
                            text: _newtext,
                            selection: TextSelection.fromPosition(TextPosition(
                                affinity: TextAffinity.downstream,
                                offset: _newtext.length)));
                      }
                    },
                    onSubmitted: (value) {
                      do some thing...
                    },
                  ),
2.wrap空間包含row問題

Warp流控件中child中包含row控件的時候,要使用MainAxisSize.min的
wrap流式布局的時候,里面使用了row進行自適應的時候,要采用上述的屬性,不然wrap中每行都會充滿,
官方注釋:

  /// Minimize the amount of free space along the main axis, subject to the
  /// incoming layout constraints.
  ///
  /// If the incoming layout constraints have a large enough
  /// [BoxConstraints.minWidth] or [BoxConstraints.minHeight], there might still
  /// be a non-zero amount of free space.
  ///
  /// If the incoming layout constraints are unbounded, and any children have a
  /// non-zero [FlexParentData.flex] and a [FlexFit.tight] fit (as applied by
  /// [Expanded]), the [RenderFlex] will assert, because there would be infinite
  /// remaining free space and boxes cannot be given infinite size.
//最小化沿主軸的空閑空間,取決于
//輸入布局約束。
///如果傳入的布局約束有足夠大
/ / / [BoxConstraints。minWidth]或[BoxConstraints。可能還會有
///是一個非零的空閑空間。
///如果傳入的布局約束是無界的,并且任何子元素都有
/ / /非零(FlexParentData。和一個[FlexFit. flex]。配合(如應用于
/// [Expanded]), [RenderFlex]將斷言,因為會有無限
///剩余的空閑空間和盒子不能被賦予無限的大小。

wrap中每個只有在邊界的時候有個強力約束,每個item沒有強約束,所以導致在wrap中使用row控件的時候,row控件會沾滿整個wrap控件的一行,充滿了item的導致,設置min使其最小化空間約束,根據(jù)自控件的內容來進行最小布局約束。

3.Flutter 標簽字體下沉Bug
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 3,vertical: 1),
      decoration: BoxDecoration(
          color: widget.tagBackGroundColor,
          borderRadius: BorderRadius.circular(3)),
      child: Text(
        widget.tagString,
        textAlign: TextAlign.center,
        style: TextStyle(color: widget.tagTextColor, fontSize: 10),
      ),
    );
  }

測試階段發(fā)現(xiàn),標簽在不同的機器上,標簽的樣式都不一樣。如果什么都不設置就會導致字體偏下。基于之前的React開發(fā)經驗,基本可以確定是字體行高導致的問題。但是Flutter Text組件沒有直接設置行高的地方,只需Text設置strutStyle,指定fontSize和外層style設置的字體一致、設置合適的height即可,height值為14/10的值。

      child: Text(
        widget.tagString,
        textAlign: TextAlign.center,
        strutStyle: StrutStyle(fontSize: 10,height: 1.4),
        style: TextStyle(color: widget.tagTextColor, fontSize: 10),
      ),

為什么height設置為1.4,因為默認fontSize為14,標簽使用字體值為10,height默認放大1.4倍。

  /// The size of text (in logical pixels) to use when obtaining metrics from the font.
  ///
  /// The [fontSize] is used to get the base set of metrics that are then used to calculated
  /// the metrics of strut. The height and leading are expressed as a multiple of
  /// [fontSize].
  ///
  /// The default fontSize is 14 logical pixels.
  final double? fontSize;
4.Flutter鴻蒙字體被截問題

視覺反饋這個頁面的時間字體被截,但是我的機器上都是好的,測試機器也是好的,然后我讓視覺把測試機拿過來現(xiàn)場調試,發(fā)現(xiàn)是鴻蒙系統(tǒng)。后來慢慢排查,找到了解決方案,只需給包裹Text的外層容器設置一層白色背景即可。

5.Flutter長數(shù)字字母省略的顯示問題

期望展示效果,單號位置,超出寬度末尾...省略展示
通常做法對Text設置overflow:

overflow: TextOverflow.ellipsis

但以上屬性的缺陷是,當遇到長數(shù)字,長字母時,會被整體省略:
利用零寬空格字符處理這個問題:

///插入零寬空格字符
  String breakWord(String word) {
    if (word == null || word.isEmpty) {
      return word;
    }
    var breakWord = ' ';
    word.runes.forEach((element) {
      breakWord += String.fromCharCode(element);
      breakWord += '\u200B';
    });
    return breakWord;
  }


text: breakWord(value),

另一種寫法

text: value.replaceAll('', '\u200B')

兩種寫法,在實際展示樣式上,視覺顯示寬度略有差異。
此外,第二種寫法,用replaceAll在處理包含emoji的字符串時會出現(xiàn)not utf-16的問題。

看情況使用以上兩種方式處理即可。

6.Flutter中設置圖片寬高失效問題

如下代碼,發(fā)現(xiàn)設置圖片寬高無效

Container(
  width: 30,
  height: 30,
  decoration: BoxDecoration(
    color: ThemeColors.halfTranslucent,
    borderRadius: BorderRadius.circular(15)),
  child: LoadAssetImage("ic_back",width: 24,height: 24,)
)

解決方案:在LoadAssetImage前再包一層即可生效

Container(
  width: 30,
  height: 30,
  decoration: BoxDecoration(
    color: ThemeColors.halfTranslucent,
    borderRadius: BorderRadius.circular(15)),
  child: Center(
    child: LoadAssetImage("ic_back",width: 24,height: 24,),
  ),
)
7.Flutter中double精度問題

背景:由于 Dart 使用了和js一樣的 IEEE 754 雙精度標準進行存儲,所以存在和JS一樣的精度計算問題

解決方案:采用decimal這個三方庫解決
  #解決精度問題
  decimal: 0.3.5
refundAmount =
  "${Decimal.parse("$amountDesc") * Decimal.parse("$refundNumber")}";
8.鍵盤遮擋問題

1.存在在輸入文字的時候,若不選擇選擇文字預覽文字情況下,直接點擊拍照,會導致在拍照界面出現(xiàn)鍵盤,無法進行收起

2.移動開單2.0側篩界面,當選擇確認按鈕的時候,一直點擊,會導致pop頁面多次的情況,導致界面進行多次返回的情況。

原因:

1.該情況,在做收起鍵盤的操作的時候,未點擊預覽文字時,直接跳轉下個界面的時候,會導致鍵盤沒有完全收起來,同時下面收起鍵盤的方法的時候,雖然收起了鍵盤,但是光標仍然存在。

SystemChannels.textInput.invokeMethod('TextInput.hide');

2.側邊頁面出現(xiàn)的時候,一直點擊確定按鈕的時候,會調多次pop方法,會導致關閉抽屜欄頁面后,頁面還會存在調用一個pop的問題,導致會產生返回上一個界面的問題。

解決

1.使用該方法,收起鍵盤的同時收起光標,在空白,滑動,點擊彈框的時候均收起鍵盤

FocusScope.of(context).requestFocus(FocusNode());

2.在點擊確定的時候,增加標志位,在頁面銷毀之前,只會調用一次。


1655715619775.jpg

防抖解決方法:

新增到公共庫里,支持自定義防抖時間,默認一秒防抖

import 'dart:async';

///按鈕防抖,milliseconds防抖時間,默認1秒
Function debounce(Function func, {int milliseconds = 1000}) {
  Timer timer;
  Function target = () {
    if (timer?.isActive ?? false) {
      timer?.cancel();
    }
    timer = Timer(Duration(milliseconds: milliseconds), () {
      func?.call();
    });
  };
  return target;
}

使用

child: GestureDetector(
       onTap: debounce(() {
       print('點擊了');
    },milliseconds:1500),
  ),
9.flutter時間格式轉換問題

//正常情況下時間格式轉字符
var selectedTimeStr =
selectedMonth ?? DateFormat('yyyy-MM').format(DateTime.now());
//可以將時間戳轉成對應的字符串

var selectedMonth = '2022-06',

//將字符串轉時間戳的時候,正常使用parse方法
var parseTime = DateTime.parse(selectedMonth);

//但是parse只能針對標準格式轉化的,比如2022-06這個就無法轉,只能轉下面標準格式,
//否則會報FormatException錯
/// * "2012-02-27"
/// * "2012-02-27 13:27:00"
/// * "2012-02-27 13:27:00.123456789z"
/// * "2012-02-27 13:27:00,123456789z"
/// * "20120227 13:27:00"
/// * "20120227T132700"
/// * "20120227"
/// * "+20120227"
/// * "2012-02-27T14Z"
/// * "2012-02-27T14+00:00"
/// * "-123450101 00:00:00 Z": in the year -12345.
/// * "2002-02-27T14:00:00-0500": Same as "2002-02-27T19:00:00Z"

//使用下面可以解決報錯問題,但是無法正確解析,返回的是now的時間格式
var tryParseTime = DateTime.tryParse(selectedMonth) ?? DateTime.now();

//使用下面的可以正常解析
var parseStrictTime = DateFormat('yyyy-MM').parseStrict(selectedMonth);

//parseStrict可以解析任意格式保持統(tǒng)一的,下面的可以解析成2022-01-01 0000000時間

selectedMonth = '2022-';
parseStrictTime =  DateFormat('yyyy-').parseStrict(selectedMonth);
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容