flustars 0.3.2

  • Readme
  • Changelog
  • Example
  • Installing
  • 96

Language: English | 中文简体

flustars(Flutter常用工具类库) #

Pub

flustars依赖于Dart常用工具类库common_utils,以及对其他第三方库封装,致力于为大家分享简单易用工具类。如果你有好的工具类欢迎PR.
目前包含SharedPreferences Util, Screen Util, Directory Util, Widget Util, Image Util。

Pub flustars

[✓] Flutter (Channel stable, v1.17.0, locale zh-Hans-CN)

使用方式: #

dependencies:
  flustars: ^0.3.2
  
import 'package:flustars/flustars.dart';

or

// git (version 0.3.2)
dependencies:
  flustars:
    git:
      url: git://github.com/Sky24n/flustars.git

Change Log #

common_utils新版本v1.2.0。
如果项目中使用了 flustars: ^0.2.6及以上版本。
删除pubspec.lock文件,直接运行flutter packages get 即可使用最新版!

common_utils v1.2.0 (未发布)
1、新增JsonUtil。
2、新增EncryptUtil 简单加解密。
3、LogUtil 更新。

String objStr = "{\"name\":\"成都市\"}";
City hisCity = JsonUtil.getObj(objStr, (v) => City.fromJson(v));
String listStr = "[{\"name\":\"成都市\"}, {\"name\":\"北京市\"}]";
List<City> cityList = JsonUtil.getObjList(listStr, (v) => City.fromJson(v));

const String key = '11, 22, 33, 44, 55, 66';
String value = 'Sky24n';
String encode = EncryptUtil.xorBase64Encode(value, key); // WH1YHgMs
String decode = EncryptUtil.xorBase64Decode(encode, key); // Sky24n

//超长log查看
common_utils e  — — — — — — — — — — — — — — — — st — — — — — — — — — — — — — — — —
common_utils e | 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,
common_utils e | 7,988,989,990,991,992,993,994,995,996,997,998,999,
common_utils e  — — — — — — — — — — — — — — — — ed — — — — — — — — — — — — — — — —

v0.3.2 remove MyAppBar。

v0.3.0 新增ImageUtil。

DirectoryUtil 改变

bool _initTempDir = false;
bool _initAppDocDir = false;
bool _initAppSupportDir = false;
bool _initStorageDir = false;

移除package参数

Flutter工具类库 flustars #

1、SpUtil : 单例"同步"SharedPreferences工具类。支持get传入默认值,支持存储对象,支持存储对象数组。
2、ScreenUtil : 屏幕适配,获取屏幕宽、高、密度,AppBar高,状态栏高度,屏幕方向.
3、WidgetUtil : 监听Widget渲染状态,获取Widget宽高,在屏幕上的坐标,获取网络/本地图片尺寸.
4、DioUtil : 单例Dio网络工具类(已迁移至此处DioUtil)。 5、ImageUtil : 获取网络/本地图片尺寸.

Dart常用工具类库 common_utils #

1、TimelineUtil : 时间轴.(新)
2、TimerUtil : 倒计时,定时任务.(新)
3、MoneyUtil : 精确转换,元转分,分转元,支持格式输出.(新)
4、LogUtil : 简单封装打印日志.(新)
5、DateUtil : 日期转换格式化输出.
6、RegexUtil : 正则验证手机号,身份证,邮箱等等.
7、NumUtil : 保留x位小数, 精确加、减、乘、除, 防止精度丢失.
8、ObjectUtil : 判断对象是否为空(String List Map),判断两个List是否相等.
9、TextUtil : TextUtil.
10、EncryptUtil : EncryptUtil.
11、JsonUtil : JsonUtil.

APIs #

getObj
getObjList
putObject
getObject
putObjectList
getObjectList
getString
putString
getBool
putBool
getInt
putInt
getDouble
putDouble
getStringList
putStringList
getDynamic
haveKey
getKeys
remove
clear
isInitialized
  
  
/// SpUtil使用:
/// 方式一
/// 等待sp初始化完成后再运行app。
/// sp初始化时间 release模式下30ms左右,debug模式下100多ms。
void main() async {
  await SpUtil.getInstance();
  runApp(MyApp());
}

class MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    /// 同步使用Sp。
    SpUtil.remove("username");
    String defName = SpUtil.getString("username", defValue: "sky");
    SpUtil.putString("username", "sky24");
    String name = SpUtil.getString("username");
    print("MyApp defName: $defName, name: $name");
  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: SplashPage(),
    );
  }
}  


/// 方式二
/// 增加闪屏页,在闪屏页SpUtil初始化完成, await SpUtil.getInstance();
/// 跳转到主页后,可以直接同步使用。 String defName = SpUtil.getString("username");
   
import 'package:flustars/flustars.dart'; 
  
/// SpUtil详细使用示例!  
void main() => runApp(MyApp());
  
class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MyAppState();
  }
}
  
class MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    _initAsync();
  }
  
  _initAsync() async {
    /// App启动时读取Sp数据,需要异步等待Sp初始化完成。
    await SpUtil.getInstance();

    /// 同步使用Sp。
    SpUtil.remove("username");
    String defName = SpUtil.getString("username", defValue: "sky");
    SpUtil.putString("username", "sky24");
    String name = SpUtil.getString("username");
    print("MyApp defName: $defName, name: $name");
  }
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      routes: {
        '/MainPage': (ctx) => MyHomePage(),
      },
      home: SplashPage(),
    );
  }
}  
  
/// 闪屏页。
class SplashPage extends StatefulWidget {
  SplashPage({Key key}) : super(key: key);
  
  @override
  _SplashPageState createState() => _SplashPageState();
}
  
class _SplashPageState extends State<SplashPage> {
  String _info = '';
  
  @override
  void initState() {
    super.initState();
    _initAsync();
  }
  
  _initAsync() async {
    /// App启动时读取Sp数据,需要异步等待Sp初始化完成。
    await SpUtil.getInstance();
    Future.delayed(new Duration(milliseconds: 500), () {
      /// 同步使用Sp。
      /// 是否显示引导页。
      if (SpUtil.getBool("key_guide", defValue: true)) {
        SpUtil.putBool("key_guide", false);
        _initBanner();
      } else {
        _initSplash();
      }
    });
  }
  
  /// App引导页逻辑。
  void _initBanner() {
    setState(() {
      _info = "引导页~";
    });
  }
  
  /// App广告页逻辑。
  void _initSplash() {
    setState(() {
      _info = "广告页,2秒后跳转到主页";
    });
    Future.delayed(new Duration(milliseconds: 2000), () {
      Navigator.of(context).pushReplacementNamed('/MainPage');
    });
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Splash"),
      ),
      body: new Center(
        child: new Text("$_info"),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          bool isGuide = SpUtil.getBool("key_guide", defValue: true);
          if (isGuide) {
            Navigator.of(context).pushReplacementNamed('/MainPage');
          }
        },
        child: Icon(Icons.navigate_next),
      ),
    );
  }
}
  
class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);
  
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
  
class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
    
    /// 同步使用Sp。
   
    /// 存取基础类型
    SpUtil.putString("username", "Sky24n");
    String userName = SpUtil.getString("username");
    print("MyHomePage userName: " + userName);
    
    bool isFirst = SpUtil.getBool("userName", defValue: true);
    SpUtil.putBool("isFirst", false);
    print("MyHomePage isFirst: $isFirst");
    
    /// save object example.
    /// 存储实体对象示例。
    City city = new City();
    city.name = "成都市";
    SpUtil.putObject("loc_city", city);
    
    City hisCity = SpUtil.getObj("loc_city", (v) => City.fromJson(v));
    print("City: " + (hisCity == null ? "null" : hisCity.toString()));
    
    /// save object list example.
    /// 存储实体对象list示例。
    List<City> list = new List();
    list.add(new City(name: "成都市"));
    list.add(new City(name: "北京市"));
    SpUtil.putObjectList("loc_city_list", list);
    
    List<City> _cityList = SpUtil.getObjList("loc_city_list", (v) => City.fromJson(v));
    print("City list: " + (_cityList == null ? "null" : _cityList.toString()));
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Home"),
      ),
      body: new Center(
        child: new Text(SpUtil.getString("username")),
      ),
    );
  }
}
  
class City {
  String name;
  
  City({this.name});
  
  /// 必须写.
  City.fromJson(Map<String, dynamic> json) : name = json['name'];
  
  /// 必须写.
  Map<String, dynamic> toJson() => {
        'name': name,
      };
  
  @override
  String toString() {
    StringBuffer sb = new StringBuffer('{');
    sb.write("\"name\":\"$name\"");
    sb.write('}');
    return sb.toString();
  }
}

getWidth                  : 返回根据屏幕宽适配后尺寸.
getHeight                 : 返回根据屏幕高适配后尺寸.
getWidthPx                : 返回根据屏幕宽适配后尺寸.
getHeightPx               : 返回根据屏幕高适配后尺寸.
getSp                     : 返回根据屏幕宽适配后字体尺寸.
screenWidth               : 获取屏幕宽.
screenHeight              : 获取屏幕高.
screenDensity             : 获取屏幕密度.
appBarHeight              : 获取系统AppBar高度.
statusBarHeight           : 获取系统状态栏高度.
getScreenW(ctx)           : 当前屏幕 宽.
getScreenH(ctx)           : 当前屏幕 高.
getStatusBarH(ctx)        : 当前状态栏高度.
getBottomBarH(ctx)        : 当前BottomBar高度.
getScaleW(ctx,size)       : 返回根据屏幕宽适配后尺寸.
getScaleH(ctx,size)       : 返回根据屏幕高适配后尺寸.
getScaleSp(ctx,size)      : 返回根据屏幕宽适配后字体尺寸.  
getScaleSp(ctx,size)      : 返回根据屏幕宽适配后字体尺寸.  

///旧适配方法仅适用于纵屏适配。
///推荐使用以下新适配方法。
getAdapterSize(size)             : 返回适配后尺寸,可用于宽,高,字体尺寸.  
getAdapterSizeCtx(ctx,size)      : 返回适配后尺寸,可用于宽,高,字体尺寸.   

double adapterSize = ScreenUtil.getInstance().getAdapterSize(100);
double adapterSize = ScreenUtil.getAdapterSizeCtx(context, 100);
  
一、不依赖context
// 屏幕宽
double screenWidth = ScreenUtil.getInstance().screenWidth;
// 屏幕高
double screenHeight = ScreenUtil.getInstance().screenHeight;
// 屏幕像素密度
double screenDensity = ScreenUtil.getInstance().screenDensity;
// 系统状态栏高度
double statusBarHeight = ScreenUtil.getInstance().statusBarHeight;
// BottomBar高度 
double bottomBarHeight = ScreenUtil.getInstance().bottomBarHeight;
// 系统AppBar高度
double appBarHeight = ScreenUtil.getInstance().appBarHeight;
// 根据屏幕宽适配后尺寸
double adapterW100 = ScreenUtil.getInstance().getWidth(100);
// 根据屏幕高适配后尺寸
double adapterH100 = ScreenUtil.getInstance().getHeight(100);
// 根据屏幕宽适配后字体尺寸
double adapterSp100 = ScreenUtil.getInstance().getSp(100);
// 根据屏幕宽适配后尺寸(输入px)
double adapterW100px = ScreenUtil.getInstance().getWidthPx(300);
// 根据屏幕高适配后尺寸(输入px)
double adapterH100px = ScreenUtil.getInstance().getHeightPx(300);
  
二、依赖context
// 屏幕宽
double screenWidth = ScreenUtil.getScreenW(context);
// 屏幕高
double screenHeight = ScreenUtil.getScreenH(context);
// 屏幕像素密度
double screenDensity = ScreenUtil.getScreenDensity(context);
// 系统状态栏高度
double statusBarHeight = ScreenUtil.getStatusBarH(context);
// BottomBar高度
double bottomBarHeight = ScreenUtil.getBottomBarH(context);
// 根据屏幕宽适配后尺寸
double adapterW100 = ScreenUtil.getScaleW(context, 100);
// 根据屏幕高适配后尺寸
double adapterH100 = ScreenUtil.getScaleH(context, 100);
// 根据屏幕宽适配后字体尺寸
double adapterSp100 = ScreenUtil.getScaleSp(context, 100);
// 屏幕方向
Orientation orientation = ScreenUtil.getOrientation(context);

  • DirectoryUtil

setInitDir
initTempDir
initAppDocDir
initAppSupportDir
initStorageDir
createDirSync
createDir
getTempPath
getAppDocPath
getAppSupportPath
getStoragePath
createTempDirSync
createAppDocDirSync
createStorageDirSync
createTempDir
createAppDocDir
createStorageDir

    await DirectoryUtil.getInstance();
    String tempPath = DirectoryUtil.getTempPath(
        category: 'Pictures', fileName: 'demo', format: 'png');
    print("thll  tempPath: $tempPath");

    String appDocPath = DirectoryUtil.getAppDocPath(
        category: 'Pictures', fileName: 'demo', format: 'png');
    print("thll  appDocPath: $appDocPath");

    String appSupportPath = DirectoryUtil.getAppSupportPath(
        category: 'Pictures', fileName: 'demo', format: 'png');
    print("thll  appSupportPath: $appSupportPath");

    String storagePath = DirectoryUtil.getStoragePath(
        category: 'Pictures', fileName: 'demo', format: 'png');
    print("thll  storagePath: $storagePath");

asyncPrepare              : Widget渲染监听,监听widget宽高变化,callback返回宽高等参数.
getWidgetBounds           : 获取widget 宽高.
getWidgetLocalToGlobal    : 获取widget在屏幕上的坐标.
getImageWH                : 获取图片宽高,加载错误情况返回 Rect.zero.(单位 px). 
getImageWHE               : 获取图片宽高,加载错误会抛出异常.(单位 px). 

/// widget渲染监听。
WidgetUtil widgetUtil = new WidgetUtil();
widgetUtil.asyncPrepare(context, true, (Rect rect) {
  // widget渲染完成。
});

/// widget宽高。
Rect rect = WidgetUtil.getWidgetBounds(context);

/// widget在屏幕上的坐标。
Offset offset = WidgetUtil.getWidgetLocalToGlobal(context);
  
/// 获取CachedNetworkImage下的图片尺寸
Image image = new Image(image: new CachedNetworkImageProvider("Url"));
Rect rect1 = await WidgetUtil.getImageWH(image: image);  

/// 其他image
Image imageAsset = new Image.asset("");
Image imageFile = new Image.file(File("path"));
Image imageNetwork = new Image.network("url");
Image imageMemory = new Image.memory(null);

/// 获取网络图片尺寸
Rect rect2 = await WidgetUtil.getImageWH(url: "Url");

/// 获取本地图片尺寸 localUrl 需要全路径
Rect rect3 = await WidgetUtil.getImageWH(localUrl: "assets/images/3.0x/ali_connors.png");

/// 其他方式
WidgetUtil.getImageWH(url: "Url").then((Rect rect) {
  print("rect: " + rect.toString();
});

WidgetUtil.getImageWHE(url: "Url").then((Rect rect) {
  print("rect: " + rect.toString();
}).catchError((error) {
  print("rect: " + error.toString();
});
  • ImageUtil

getImageWH
// 打开debug模式.
DioUtil.openDebug(); 

// 配置网络参数.
Options options = DioUtil.getDefOptions();
options.baseUrl = "http://www.wanandroid.com/";
HttpConfig config = new HttpConfig(options: options);
DioUtil().setConfig(config);
  
// 两种单例请求方式.
DioUtil().request<List>(Method.get, "banner/json");
DioUtil.getInstance().request(Method.get, "banner/json");
  
//示例
LoginReq req = new LoginReq('username', 'password');
DioUtil().request(Method.post, "user/login",data: req.toJson());
  
//示例
FormData formData = new FormData.from({
      "username": "username",
      "password": "password",
    });
DioUtil().requestR(Method.post, "user/login",data: rformData);
  
// 网络请求日志  
I/flutter ( 5922): ----------------Http Log----------------
I/flutter ( 5922): [statusCode]:   200
I/flutter ( 5922): [request   ]:   method: GET  baseUrl: http://www.wanandroid.com/  path: lg/collect/list/0/json
I/flutter ( 5922): [reqdata   ]:   null
I/flutter ( 5922): [response  ]:   {data: {curPage: 1, datas: [], offset: 0, over: true, pageCount: 0, size: 20, total: 0}, errorCode: 0, errorMsg: }

Flutter Demos #

  • |--demos
    • |-- city_select_page.dart 城市列表(索引&悬停)示例
    • |-- date_page.dart 日期格式化示例
    • |-- image_size_page.dart 获取网络/本地图片尺寸示例
    • |-- money_page.dart 金额(元转分/分转元)示例
    • |-- pinyin_page.dart 汉字转拼音示例
    • |-- regex_page.dart 正则工具类示例
    • |-- round_portrait_page.dart 圆形圆角头像示例
    • |-- timeline_page.dart 时间轴示例
    • |-- timer_page.dart 倒计时/定时任务示例
    • |-- widget_page.dart 获取Widget尺寸/屏幕坐标示例

点击下载APK : v0.1.x #

扫码下载APK : #

flutter_wanandroid

Screenshots #



关于作者 #

GitHub : Sky24n
简书     : Sky24n
掘金     : Sky24n
Pub      : Sky24n

如果您觉得本项目不错的话,来个star支持下作者吧!

Flutter全局屏幕适配 auto_size

GitHub stars GitHub forks GitHub watchers

Flutter版玩安卓 flutter_wanandroid

GitHub stars GitHub forks GitHub watchers

Flutter仿滴滴出行 GreenTravel

GitHub stars GitHub forks GitHub watchers

Flutter常用工具类库 flustars

GitHub stars GitHub forks GitHub watchers

Dart常用工具类库 common_utils

GitHub stars GitHub forks GitHub watchers

Flutter城市列表 azlistview

GitHub stars GitHub forks GitHub watchers

Flutter汉字转拼音库 lpinyin

GitHub stars GitHub forks GitHub watchers

Flutter国际化库 fluintl

GitHub stars GitHub forks GitHub watchers

0.3.2 #

  • TODO: remove MyAppBar.

0.3.1 #

  • TODO: add ImageUtil, Refactor DirectoryUtil.

0.2.6+2 #

  • TODO: fix minimum version dependency.

0.2.6+1 #

  • TODO: fix path_provider compatible.

0.2.6 #

  • TODO: dependencies common_utils ,new DirectoryUtil, SpUtil add getObj,getObjList, ScreenUtil add getAdapterSize, getAdapterSizeCtx.

0.2.5+1 #

  • TODO: fix WidgetUtil error with flutter v1.6.3.

0.2.5 #

  • TODO: WidgetUtil add getImageWH(x,x,x,x).

0.2.4 #

  • TODO: synchronized : >=0.1.0 - 3.0.0 shared_preferences >= 0.1.1 - 1.0.0

0.2.3 #

  • TODO: synchronized : any , shared_preferences : any , SpUtil add putObject,getObject,putObjectList,getObjectList。

0.2.2 #

  • TODO: SpUtil add get default value.

0.1.9 #

  • TODO: remove DioUtil.

0.1.8 #

  • TODO: fix ScreenUtil bug, Dio v1.0.13.

0.1.7 #

  • TODO: Dio v1.0.12.

0.1.6 #

  • TODO: Dio Util, print http log, singleton mode.

0.1.5 #

  • TODO: Screen adaptation,屏幕适配.

0.1.4 #

  • TODO: ScreenUtil update. UI MyAppBar.

0.1.3 #

  • TODO: Health updated.

0.1.2 #

  • TODO: SpUtil updated.

0.1.0 #

  • TODO: Contains SpUtil,ScreenUtil,WidgetUtil.

0.0.1 #

  • TODO: Describe initial release.

example/lib/main.dart

import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class City {
  String name;

  City({this.name});

  /// must.
  City.fromJson(Map<String, dynamic> json) : name = json['name'];

  /// must.
  Map<String, dynamic> toJson() => {
        'name': name,
      };

  @override
  String toString() {
    StringBuffer sb = StringBuffer('{');
    sb.write("\"name\":\"$name\"");
    sb.write('}');
    return sb.toString();
  }
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    _initAsync();

    /// 配置设计稿尺寸
    /// 如果设计稿尺寸默认配置一致,无需该设置。默认 width:360.0 / height:640.0 / density:3.0
    /// Configuration design draft size.
    /// If the default configuration of design draft size is the same, this setting is not required. default width:360.0 / height:640.0 / density:3.0
    setDesignWHD(360.0, 640.0, density: 3);
  }

  /// SpUtil example.
  void _initAsync() async {
    await SpUtil.getInstance();

    SpUtil.putString("username", "sky24");
    String userName = SpUtil.getString("username", defValue: "");
    print("thll userName: " + userName);

    /// save object example.
    /// 存储实体对象示例。
    City city = City();
    city.name = "成都市";
    SpUtil.putObject("loc_city", city);

    City hisCity = SpUtil.getObj("loc_city", (v) => City.fromJson(v));
    print("thll City: " + (hisCity == null ? "null" : hisCity.toString()));

    /// save object list example.
    /// 存储实体对象list示例。
    List<City> list = List();
    list.add(City(name: "成都市"));
    list.add(City(name: "北京市"));
    SpUtil.putObjectList("loc_city_list", list);

    List<City> dataList =
        SpUtil.getObjList("loc_city_list", (v) => City.fromJson(v));
    print(
        "thll CityList: " + (dataList == null ? "null" : dataList.toString()));
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MainPage(),
    );
  }
}

class MainPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MainPageState();
  }
}

/// 在MainPage使用依赖不context方法获取屏幕参数及适配,需要build方法内调用[MediaQuery.of(context)]。
/// 或者使用依赖context方法获取屏幕参数及适配。
/// In MainPage, the dependency-free context method is used to obtain screen parameters and adaptions, which requires a call to [MediaQuery. of (context)] within the build method.
/// Or use context-dependent methods to obtain screen parameters and adaptions.
class MainPageState extends State<MainPage> {
  void test2() async {
    print("thll xxxxxxxxxxx test7......");
    await DirectoryUtil.getInstance();
    String tempPath = DirectoryUtil.getTempPath(
        category: 'Pictures', fileName: 'demo', format: 'png');
    print("thll  tempPath: $tempPath");

    String appDocPath = DirectoryUtil.getAppDocPath(
        category: 'Pictures', fileName: 'demo', format: 'png');
    print("thll  appDocPath: $appDocPath");

    String appSupportPath = DirectoryUtil.getAppSupportPath(
        category: 'Pictures', fileName: 'demo', format: 'png');
    print("thll  appSupportPath: $appSupportPath");

    String storagePath = DirectoryUtil.getStoragePath(
        category: 'Pictures', fileName: 'demo', format: 'png');
    print("thll  storagePath: $storagePath");
  }

  @override
  void initState() {
    super.initState();
    test2();
  }

  void test() async {
    String _src =
        "https://dsd361-oss1.oss-cn-beijing.aliyuncs.com/upload/advert/2d56ad78-472d-4eaf-b1f1-9a6887089d17.gif";

    Rect rect2 = await WidgetUtil.getImageWH(url: _src);

//    ImageUtil imageUtil = ImageUtil();
//    imageUtil.getImageWH().then((Rect rect) {});
  }

  @override
  Widget build(BuildContext context) {
    /// 如果使用依赖不context方法获取屏幕参数及适配,需要调用此方法。
    /// If you use a dependent context-free method to obtain screen parameters and adaptions, you need to call this method.
    MediaQuery.of(context);

    double statusBar = ScreenUtil.getInstance().statusBarHeight;
    double width = ScreenUtil.getInstance().screenWidth;
    double height = ScreenUtil.getInstance().screenHeight;
    double density = ScreenUtil.getInstance().screenDensity;
    double sp = ScreenUtil.getInstance().getAdapterSize(24);
    double spc = ScreenUtil.getInstance().getAdapterSize(24);
    double adapterW = ScreenUtil.getInstance().getAdapterSize(360);

    print(
        "thll  MainPage statusBar: $statusBar, width: $width, height: $height, density: $density, sp: $sp, spc: $spc, adapterW: $adapterW");
    return Scaffold(
      // 一个不需要GlobalKey就可以openDrawer的AppBar
      appBar: AppBar(
        leading: Builder(builder: (BuildContext ctx) {
          return IconButton(
              icon: ClipOval(
                child: Image.asset(('assets/images/ali_connors.png')),
              ),
              onPressed: () {
                Scaffold.of(ctx).openDrawer();
              });
        }),
        title: const Text('Flustars Demos'),
        centerTitle: true,
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.search),
            onPressed: () {
              print("thll onPressed......");
              //test2();
              test();
//              Navigator.push(context,
//                  CupertinoPageRoute<void>(builder: (ctx) => SecondPage()));
            },
          ),
        ],
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            width: 360.0,
            height: 50,
            color: Colors.grey,
            child: Center(
              child: Text(
                "未适配宽",
                style: TextStyle(fontSize: 24.0),
              ),
            ),
          ),
          Container(
            width: ScreenUtil.getInstance().getAdapterSize(360.0),
            height: 50,
            color: Colors.grey,
            child: Center(
              child: Text(
                "已适配宽",
                style: TextStyle(fontSize: 24.0),
              ),
            ),
          ),
          Container(
            width: 100,
            height: 100,
            color: Colors.grey,
            child: Center(
              child: Text(
                "你好你好你好",
                style: TextStyle(fontSize: 24.0),
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 10.0),
            width: ScreenUtil.getInstance().getAdapterSize(100.0),
            height: ScreenUtil.getInstance().getAdapterSize(100.0),
            color: Colors.grey,
            child: Center(
              child: Text(
                "你好你好你好",
                style: TextStyle(
                    fontSize: ScreenUtil.getInstance().getAdapterSize(24.0)),
              ),
            ),
          ),
        ],
      ),
      drawer: MyDrawer(),
    );
  }
}

class MyDrawer extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    double statusBar = ScreenUtil.getInstance().statusBarHeight;
    double width = ScreenUtil.getInstance().screenWidth;
    double height = ScreenUtil.getInstance().screenHeight;
    print(
        " thll  MyDrawer statusBar: $statusBar, width: $width, height: $height");

    return Container(
      color: Colors.white,
      width: ScreenUtil.getInstance().getWidth(240),
      child: ListView(
        padding: EdgeInsets.zero,
        children: <Widget>[
          Container(
            color: Colors.teal,
            padding:
                EdgeInsets.only(top: ScreenUtil.getInstance().statusBarHeight),
            child: Center(
              child: Text(
                "Sky24n",
                style: TextStyle(fontSize: 16, color: Colors.white),
              ),
            ),
            height: 160,
          )
        ],
      ),
    );
  }
}

class SecondPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return SecondPageState();
  }
}

class SecondPageState extends State<SecondPage> {
  @override
  void initState() {
    super.initState();
    _init();
//    _initWithCtx();
  }

  void _init() {
    double screenWidth = ScreenUtil.getInstance().screenWidth;
    double screenHeight = ScreenUtil.getInstance().screenHeight;
    double screenDensity = ScreenUtil.getInstance().screenDensity;
    double statusBarHeight = ScreenUtil.getInstance().statusBarHeight;
    double bottomBarHeight = ScreenUtil.getInstance().bottomBarHeight;
    double appBarHeight = ScreenUtil.getInstance().appBarHeight;
    double adapterW100 = ScreenUtil.getInstance().getWidth(100);
    double adapterH100 = ScreenUtil.getInstance().getHeight(100);
    double adapterSp100 = ScreenUtil.getInstance().getSp(100);
    double adapterW100px = ScreenUtil.getInstance().getWidthPx(300);
    double adapterH100px = ScreenUtil.getInstance().getHeightPx(300);

    print("thll  SecondPage _init screenWidth: $screenWidth, screenHeight: $screenHeight, screenDensity: $screenDensity" +
        ", statusBarHeight: $statusBarHeight, bottomBarHeight: $bottomBarHeight, appBarHeight: $appBarHeight" +
        ", adapterW100: $adapterW100, adapterH100: $adapterH100, adapterSp100: $adapterSp100" +
        ", adapterW100px: $adapterW100px, adapterH100px: $adapterH100px");
  }

  void _initWithCtx() {
    double screenWidth = ScreenUtil.getScreenW(context);
    double screenHeight = ScreenUtil.getScreenH(context);
    double screenDensity = ScreenUtil.getScreenDensity(context);
    double statusBarHeight = ScreenUtil.getStatusBarH(context);
    double bottomBarHeight = ScreenUtil.getBottomBarH(context);
    double adapterW100 = ScreenUtil.getScaleW(context, 100);
    double adapterH100 = ScreenUtil.getScaleH(context, 100);
    double adapterSp100 = ScreenUtil.getScaleSp(context, 100);
    Orientation orientation = ScreenUtil.getOrientation(context);

    print("thll  SecondPage _initWithCtx screenWidth: $screenWidth, screenHeight: $screenHeight, screenDensity: $screenDensity" +
        ", statusBarHeight: $statusBarHeight, bottomBarHeight: $bottomBarHeight" +
        ", adapterW100: $adapterW100, adapterH100: $adapterH100, adapterSp100: $adapterSp100");
  }

  @override
  Widget build(BuildContext context) {
    double statusBar = ScreenUtil.getInstance().statusBarHeight;
    double width = ScreenUtil.getInstance().screenWidth;
    double height = ScreenUtil.getInstance().screenHeight;
    print(
        "thll  SecondPage statusBar: $statusBar, width: $width, height: $height");

    return Scaffold(
      appBar: AppBar(
        title: Text("Second Page"),
        centerTitle: true,
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            width: 100,
            height: 100,
            color: Colors.grey,
            child: Center(
              child: Text(
                "你好你好你好",
                style: TextStyle(fontSize: 24.0),
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 10.0),
            width: ScreenUtil.getInstance().getAdapterSize(100.0),
            height: ScreenUtil.getInstance().getAdapterSize(100.0),
            color: Colors.grey,
            child: Center(
              child: Text(
                "你好你好你好",
                style: TextStyle(
                    fontSize: ScreenUtil.getInstance().getAdapterSize(24.0)),
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 10.0),
            width: ScreenUtil.getAdapterSizeCtx(context, 100.0),
            height: ScreenUtil.getAdapterSizeCtx(context, 100.0),
            color: Colors.grey,
            child: Center(
              child: Text(
                "你好你好你好",
                style: TextStyle(
                    fontSize: ScreenUtil.getAdapterSizeCtx(context, 24.0)),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  flustars: ^0.3.2

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:flustars/flustars.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
93
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
96
Learn more about scoring.

We analyzed this package on May 24, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.1
  • pana: 0.13.8-dev
  • Flutter: 1.17.0

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=1.19.0 <3.0.0
common_utils >=1.1.0 <3.0.0 1.2.0
flutter 0.0.0
path_provider >=1.2.0 <3.0.0 1.6.9
shared_preferences >=0.4.1 <3.0.0 0.5.7+3
synchronized >=1.5.1 <4.0.0 2.2.0
Transitive dependencies
charcode 1.1.3
collection 1.14.12
convert 2.1.1
crypto 2.1.5
decimal 0.3.5
flutter_web_plugins 0.0.0
meta 1.1.8
path_provider_macos 0.0.4+3
path_provider_platform_interface 1.0.2
platform 2.2.1
plugin_platform_interface 1.0.2
rational 0.3.8
shared_preferences_macos 0.0.1+9
shared_preferences_platform_interface 1.0.4
shared_preferences_web 0.1.2+7
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8