6.屏幕适配
屏幕适配框架
flutter_screenutil
链接:https://github.com/OpenFlutter/flutter_screenutil
用法
(1)需要在每个使用的地方进行导入:
import 'package:flutter_screenutil/flutter_screenutil.dart';
(2)在build中初始化设置尺寸
在使用之前请设置好设计稿的宽度和高度,传入设计稿的宽度和高度,注意单位是px。(以750*1334为例)
ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
(3)适配尺寸
这时候我们使用的尺寸是px.
根据屏幕宽度适配:width:ScreenUtil().setWidth(540);
根据屏幕高度适配:height:ScreenUtil().setHeight(200);
适配字体大小:fontSize:ScreenUtil().setSp(28,false);
配置字体大小的参数false是不会根据系统的"字体大小"辅助选项来进行缩放。
根据学到的知识,来设置一下昨天的轮播图片问题。
首先在home_page.dart里,用import进行引入。
在build方法里,初始化设计稿尺寸,ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);.
给Container设置高和宽的值height: ScreenUtil().setHeight(333),和width: ScreenUtil().setWidth(750),
全部代码如下:
import 'package:flutter/material.dart';
import '../service/service_method.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'dart:convert';
import 'package:flutter_screenutil/flutter_screenutil.dart';
class HomePage extends StatefulWidget {
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('百姓生活+'),),
body:FutureBuilder(
future:getHomePageContent(),
builder: (context,snapshot){
if(snapshot.hasData){
var data=json.decode(snapshot.data.toString());
List<Map> swiperDataList = (data['data']['slides'] as List).cast(); // 顶部轮播组件数
return Column(
children: <Widget>[
SwiperDiy(swiperDataList:swiperDataList ), //页面顶部轮播组件
],
);
}else{
return Center(
child: Text('加载中'),
);
}
},
)
);
}
}
// 首页轮播组件编写
class SwiperDiy extends StatelessWidget {
final List swiperDataList;
SwiperDiy({Key key,this.swiperDataList}):super(key:key);
@override
Widget build(BuildContext context) {
ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
return Container(
height: ScreenUtil().setHeight(333),
width: ScreenUtil().setWidth(750),
child: Swiper(
itemBuilder: (BuildContext context,int index){
return Image.network("${swiperDataList[index]['image']}",fit:BoxFit.fill);
},
itemCount: swiperDataList.length,
pagination: new SwiperPagination(),
autoplay: true,
),
);
}
}
其他属性
我们在简单的学习一下ScreenUtil的其他属性,有助于你在工作中的灵活使用。
ScreenUtil.pixelRatio : 设备的像素密度
ScreenUtil.screenWidth : 设备的宽度
ScreenUtil.screenHeight : 设备高度
我们就简单介绍这三个吧,剩下的有些API如果感兴趣,可以到github上自行学习一下。
ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
print('设备宽度:${ScreenUtil.screenWidth}');
print('设备高度:${ScreenUtil.screenHeight}');
print('设备像素密度:${ScreenUtil.pixelRatio}');