美文网首页
Flutter 开发日常 code tips

Flutter 开发日常 code tips

作者: _烩面_ | 来源:发表于2021-08-13 12:39 被阅读0次

1、支持横竖屏设置

// 必须要保证 WidgetsFlutterBinding 被初始化,否则横竖屏设置不生效
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);

注意:WidgetsFlutterBinding 必须要保证初始化,否则横竖屏设置代码不生效。

2、获取 widget 的 size 和 position

首先,需要给 widget 设置 key

GlobalKey _customKey = GlobalKey();

Positioned(
      key: _customKey,
      left: 0,
      right: 0,
      top: 0,
      bottom: 140,
      ......
)

然后获取该 widget 的 size 和 position

@override
initState(){
   WidgetsBinding.instance.addPostFrameCallback((timeStamp) { 
     _afterLayout();
    });
   super.initState();
}
  
_afterLayout() {
   _getSize();
   _getPosition();
}

_getSize() {
    final RenderBox renderBox = _customKey.currentContext.findRenderObject();
    final sizeGreen = renderBox.size;
    print("SIZE of green: $sizeGreen");
}

_getPosition() {
    final RenderBox renderBox = _customKey.currentContext.findRenderObject();
    final positionGreen = renderBox.localToGlobal(Offset.zero);
    print("POSITION of green: $positionGreen");
}

3、获取图片的宽和高

image.image.resolve(new ImageConfiguration()).addListener(
      new ImageStreamListener((ImageInfo info, bool _) {
    m.width = info.image.width;
    m.height = info.image.height;
    this.sendMsg(m);
}));

Flutter图片宽高获取

4、Flutter 类型判断

var foo = 42;
if (foo is int) {
  print("整型");
}
switch (foo.runtimeType) {
  case int: {
    print("整型");
  }
}

相关文章

网友评论

      本文标题:Flutter 开发日常 code tips

      本文链接:https://www.haomeiwen.com/subject/zvkzvltx.html