[toc]
Flutter代码开发规范 一、目录 目录结构请查看:项目目录结构规范
二、文件+类命名 1、类文件命名 查看dart源码发现,源文件名都是小写英文加上下划线组成 ,如app_bar.dart;
使用小写加下划线来命名库和源文件
1 2 3 4 5 app_bar.dart AppBar.dart
2、资源文件命名 命名:功能名称 _ 控件类型 _ 自定义参数*(标准或者大字版).png
1 2 标准:share_btn_weixin.png 选中:share_btn_weixin_selected.png
三、类 1、class命名 一般情况下,类名是源文件名的大驼峰写法 ,如源文件app_bar.dart,类名AppBar;源文件bottom_app_bar,类名BottomAppBar;
2、import 2.1、import顺序 为了使你的文件前言保持整洁,我们有规定的命令,指示应该出现在其中。每个“部分”应该用空行分隔。
1 2 3 4 5 6 7 8 9 10 11 12 13 import 'dart:async' ; import 'dart:html' ; import 'package:bar/bar.dart' ; import 'package:foo/foo.dart' ; import 'package:my_package/util.dart' ; export 'src/error.dart' ;
2.2、import as 使用小写加下划线来命名导入前缀
1 2 3 4 5 6 7 8 9 import 'dart:math' as math; import 'package:angular_components/angular_components' as angular_components; import 'dart:math' as Math; import 'package:angular_components/angular_components' as angularComponents;
3、构造函数 3.1、构造函数定义 构造函数
1 2 3 4 5 6 7 8 9 10 11 12 class Point { num x, y; Point2(this .x, this .y); Point2(num x, num y) { this .x = x; this .y = y; } }
3.2、构造函数设计技巧 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 class WishPublishPage extends BJHBasePage { final bool isUpdateBusiness; final WishDetailModel wishDetailModel; final bool reEditPublish; final Function backCallBack; WishPublishPage({ Key key, this .isUpdateBusiness = false , this .reEditPublish = false , this .wishDetailModel, this .backCallBack, }) : super (key: key); WishPublishPage.fromOtherUser({ Key key, this .reEditPublish = false , this .isUpdateBusiness = false , this .wishDetailModel, List <WishGood> selectGoodsList, this .backCallBack, }) : super (key: key) { wishDetailModel.wishGoods = selectGoodsList; } @override _WishPublishPageState createState() => _WishPublishPageState(); }
四、其他命名 1、常量、变量命名 使用小驼峰法命名
1.1、常量 1 2 3 const num pi = 3.14 ;const int defaultTimeout = 1000 ;final RegExp urlScheme = RegExp ('^([a-z]+)
1.2、变量 1 2 3 List <String > bookList;Map <String , dynamic > bookMap;bool isShowDetail;
非特殊需要,禁止使用dynamic。(无法发挥空安全优势)
1 2 3 4 5 6 7 8 9 10 dynamic string1 = sp.getString();if ( string1.length == 2 )string1 出现 null String ? string1 = sp.getString();if ( string1 != null && string1!.length == 2 )
1.3、枚举命名 1 2 3 4 5 enum Direction { top, left, }
五、基础接口使用规范 判空(不使用length)
1 2 3 4 5 6 7 if (lunchBox.isEmpty) return 'so hungry...' ; if (words.isNotEmpty) return words.join(' ' ); if (lunchBox.length == 0 ) return 'so hungry...' ; if (!words.isEmpty) return words.join(' ' );
End