flutter多端适配
公司需要app能适配web端,而且样式得不一样,这时就需要 :
pubspec.yaml
引入库responsive_builder。
- 代码引用
import 'package:responsive_builder/responsive_builder.dart';
- ResponsiveBuilder使用如下,可以根据参数sizingInformation的deviceScreenType属性来判断设备环境,返回不同容器
ResponsiveBuilder( builder: (context, sizingInformation) { if (sizingInformation.deviceScreenType == DeviceScreenType.desktop) { return Container( color: Colors.blue, child: Text("desktop"), // pc端 ); } if (sizingInformation.deviceScreenType == DeviceScreenType.tablet) { return Container( color: Colors.red, child: Text("tablet"), //平板 ); } if (sizingInformation.deviceScreenType == DeviceScreenType.watch) { return Container( color: Colors.yellow, child: Text("watch"), //手表 ); } return Container( color: Colors.green, child: Text("mobile"), // 手机端 ); }, ), ``` 以上代码,可以在不同尺寸的情况下,返回不同的Container.
在responsive_builder库中,它帮我们定义了widget wrapper包装类,我们只需要调用ScreenTypeLayout,然后在不同分类中传入对应的布局,就可以在不同机型上完成布局的适配,有两种方式,mobile为必传布局
// Construct and pass in a widget per screen type ScreenTypeLayout( mobile: Container(color:Colors.blue) tablet: Container(color: Colors.yellow), desktop: Container(color: Colors.red), watch: Container(color: Colors.purple), ); // Construct and pass in a widget builder per screen type ScreenTypeLayout.builder( mobile: (BuildContext context) => Container(color:Colors.blue), tablet: (BuildContext context) => Container(color:Colors.yellow), desktop: (BuildContext context) => Container(color:Colors.red), watch: (BuildContext context) => Container(color:Colors.purple), );
如果说,我们并不是需要修改布局,仅仅是布局相同只是有些尺寸在不同屏幕上不同,间距不同而已。这里也提供了方法。
Container( padding: EdgeInsets.all(getValueForScreenType<double>( context: context, mobile: 10, tablet: 30, desktop: 60, ) ), child: Text('Best Responsive Package'), )
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话