flutter多端适配

公司需要app能适配web端,而且样式得不一样,这时就需要 :

  1. pubspec.yaml引入库 responsive_builder。
  2. 代码引用 import 'package:responsive_builder/responsive_builder.dart';
  3. 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'),
)

 

posted @ 2023-06-11 15:24  方小川  阅读(206)  评论(0编辑  收藏  举报