首页 > 其他分享 >flutter响应式

flutter响应式

时间:2023-12-25 15:36:27浏览次数:40  
标签:return width child 响应 Offset constraints flutter size

1 LayoutBuilder

作用比较类似css的@media ,根据不同的尺寸渲染不同的节点

LayoutBuilder(
	builder:(BuildContext context, constraints) { 
    print(constraints);  // BoxConstraints(0.0<=w<=360.0, 0.0<=h<=692.0)
  	 print(constraints.maxHeight);
     print(constraints.minHeight);
     print(constraints.maxWidth);
     print(constraints.minWidth);
    return constraints.minWidth>200?  Text('big one'): Text('small one');
  },
)


The builder function is called in the following situations:

  • The first time the widget is laid out. // 初次渲染
  • When the parent widget passes different layout constraints. // constraints发生变化
  • When the parent widget updates this widget. // 父组件更新
  • When the dependencies that the builder function subscribes to change. // builder函数中的依赖(状态等)改变

The builder function is not called during layout if the parent passes the same constraints repeatedly.

2  MediaQuery

根据系统信息,渲染不同的样式,如屏幕尺寸,手机横纵方向....

f the widget only requires a subset of properties of the MediaQueryData object, it is preferred to use the specific methods (for example: MediaQuery.sizeOf and MediaQuery.paddingOf), as those methods will not cause a widget to rebuild when unrelated properties are updated.

MediaQuery.removePadding 去掉安全距离
MediaQuery.removePadding({
  Key? key,
  required BuildContext context,
  bool removeLeft = false,
  bool removeTop = false,
  bool removeRight = false,
  bool removeBottom = false,
  required Widget child,
});
MediaQuery.of(context) 从context获取当前系统信息
size: 屏幕尺寸
devicePixelRatio: 屏蔽像素百分比
platformBrightness: 明暗风格(正常模式、黑暗模式)
orientation: 屏幕方向
viewInsets 为键盘弹出时等遮挡屏幕边距,其中 viewInsets.bottom 为键盘高度


3 使用一些组件来自适应布局


  • FittedBox

类似css 的Object.fit,确定子集的布局方式

FittedBox(fit:ObjectFit.xxx,child:xxx)
  • AspectRatio

根据宽高比布局

AspectRatio(
	aspectRatio: 0.5,
  child: Container(
    width: 100.0,
    height: 50.0,
    color: Colors.green,
  ),
 ),
  • Flex布局(Expanded+Row等)

不在这里细说


  • FractionallySizedBox
FractionallySizedBox(
        widthFactor: 0.5, // 宽度因子
        heightFactor: 0.5, // 高度因子
        alignment: FractionalOffset.center, // 排列
        child: DecoratedBox(
          decoration: BoxDecoration(
            border: Border.all(
              color: Colors.blue,
              width: 4,
            ),
          ),
        ),
      ),

4 一些响应式布局的widget

  • CustomSingleChildLayout

(还没用过,没有遇到类似的使用场景)

class CusLayout extends SingleChildLayoutDelegate {
  @override
  BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
    return super.getConstraintsForChild(constraints);
  }

  @override
  Size getSize(BoxConstraints constraints) {
    constraints =constraints *10; // 修改原来的constraints  
    return super.getSize(constraints);
  }

  @override
  Offset getPositionForChild(Size size, Size childSize) {
    // 根据size修改定位
  	if(xxx){
    	 return Offset(100,100);
    }
    // return super.getPositionForChild(size, childSize);
    return Offset(50,50);
  }

  @override
  bool shouldRelayout(covariant SingleChildLayoutDelegate oldDelegate) {
    return false;
  }
}


CustomSingleChildLayout(child:xxx,delegate:CusLayout())
  • CustomMultiChildLayout

类似CustomSingleChildLayout

// 官方示例(比较完整)下边仅仅粘贴个示例
// https://api.flutter-io.cn/flutter/widgets/CustomMultiChildLayout-class.html

class _CascadeLayoutDelegate extends MultiChildLayoutDelegate {
  _CascadeLayoutDelegate({
    required this.colors,
    required this.overlap,
    required this.textDirection,
  });

  final Map<String, Color> colors;
  final double overlap;
  final TextDirection textDirection;

  @override
  void performLayout(Size size) {
    final double columnWidth = size.width / colors.length;
    Offset childPosition = Offset.zero;
    switch (textDirection) {
      case TextDirection.rtl:
        childPosition += Offset(size.width, 0);
      case TextDirection.ltr:
        break;
    }
    for (final String color in colors.keys) {
      // layoutChild must be called exactly once for each child.
      final Size currentSize = layoutChild(
        color,
        BoxConstraints(maxHeight: size.height, maxWidth: columnWidth),
      );
      // positionChild must be called to change the position of a child from
      // what it was in the previous layout. Each child starts at (0, 0) for the
      // first layout.
      switch (textDirection) {
        case TextDirection.rtl:
          positionChild(color, childPosition - Offset(currentSize.width, 0));
          childPosition +=
              Offset(-currentSize.width, currentSize.height - overlap);
        case TextDirection.ltr:
          positionChild(color, childPosition);
          childPosition +=
              Offset(currentSize.width, currentSize.height - overlap);
      }
    }
  }

  // shouldRelayout is called to see if the delegate has changed and requires a
  // layout to occur. Should only return true if the delegate state itself
  // changes: changes in the CustomMultiChildLayout attributes will
  // automatically cause a relayout, like any other widget.
  @override
  bool shouldRelayout(_CascadeLayoutDelegate oldDelegate) {
    return oldDelegate.textDirection != textDirection ||
        oldDelegate.overlap != overlap;
  }
}

CustomMultiChildLayout(
      delegate: _CascadeLayoutDelegate(
        colors: _colors,
        overlap: 30.0,
        textDirection: Directionality.of(context),
      ),
      children:xxx)



  • OrientationBuilder

根据手机横纵向布局

OrientationBuilder(builder(BuildContext context,
Orientation orientation){
	if(xxx){
  	return
  }
})



5 其他

插件 flutter_screenutil  设置基本尺寸(设计图尺寸),根据屏幕的比例来调整实际渲染尺寸。类似web html的rem布局方案。

标签:return,width,child,响应,Offset,constraints,flutter,size
From: https://blog.51cto.com/u_16406280/8968920

相关文章

  • Flutter Icons交错动画
    import'package:flutter/material.dart';classAnimateIconsextendsStatelessWidget{constAnimateIcons({super.key});@overrideWidgetbuild(BuildContextcontext){returnScaffold(appBar:AppBar(title:constText(�......
  • 26、Flutter中命名路由
    Flutter中的命名路由main.dart中配置路由voidmain(){runApp(MaterialApp(theme:ThemeData(appBarTheme:constAppBarTheme(color:Colors.blue,//设置导航栏颜色(新版本的设置方法)),),//home:Scaffold(body:MyFlutter1())......
  • 25、Flutter中基本路由
    Flutter路由介绍Flutter中的路由通俗的讲就是页面跳转。在Flutter中通过Navigator组件管理路由导航。并提供了管理堆栈的方法。如:Navigator.push和Navigator.popFlutter中给我们提供了两种配置路由跳转的方式:1、基本路由2、命名路由Flutter中的基本路由使用想从HomePage......
  • flutter中背景图片(动态图片)
    单页面设置背景图片使用 Container 组件和 decoration 属性:优点:简单易用,适用于大多数情况下的页面背景设置。缺点:无法控制背景图片的位置和层级。classMyBookextendsStatelessWidget{constMyBook({super.key});@overrideWidgetbuild(BuildContextcontex......
  • Flutter中 关于package:flutter/cupertino.dart和package:flutter/material.dart的区
    import'package:flutter/cupertino.dart';和import'package:flutter/material.dart';这两个语句分别用于导入Flutter框架中的不同部分,而且它们通常用于创建不同风格的用户界面。1.import'package:flutter/material.dart';:这是导入Material部分的语句,Material是一种设计......
  • flutter 桌面通知 气泡消息数量
    先上效果原理Android操作系统提供的NotificationManager接口来设置应用程序图标上的徽章iOS操作系统提供的UIApplication.shared.applicationIconBadgeNumber使用flutterflutterpubaddflutter_app_badger通过在启动退出时候更新气泡import'package......
  • Jmeter:响应断言
    一前言环境:window10jmeter5.3对jmeter响应断言中的一些字段进行简单说明二响应断言例子还是拿之前的httpbin.org为例子看结果没有红色提示,表示断言没有问题,请求的响应也有对应的数据响应断言相应断言里面字段很多,经常容易搞混名称和注释随心情随便写applyto:......
  • 委托协议栈发送接受数据响应
    前景提要上一篇文章说过网络收发功能是委托操作系统实现的,这里的委托就是指委托操作系统的协议栈,和DNS查询一样,建立连接和通信上层也需要使用到Socket的,Socket用于提供计算机之间连接通信的管道,大致示意图如下所示:上图表示收发数据的主要思路,那么要通信就需要先建立这条管道(也叫......
  • HTML学习第三天:探索语义化标签与响应式设计
    在今天的HTML学习中,我进一步了解了语义化标签和响应式设计的重要性。早上,我开始学习语义化标签。这些标签不仅可以定义网页的结构,还能为搜索引擎和辅助技术提供信息。例如,<header>标签用于定义页面的头部,<nav>标签用于定义导航菜单。这些标签不仅提高了代码的可读性,还有助于提高网......
  • 【Spring教程29】Spring框架实战:从零开始学习SpringMVC 之 服务器响应知识全面详解
    目录1环境准备2响应页面3返回文本数据4响应JSON数据5知识点总结欢迎大家回到《Java教程之Spring30天快速入门》,本教程所有示例均基于Maven实现,如果您对Maven还很陌生,请移步本人的博文《如何在windows11下安装Maven并配置以及IDEA配置Maven环境》,本文的上一篇为《SpringMVC......