diff --git a/FRouter/FRouter.dart b/FRouter/FRouter.dart new file mode 100644 index 0000000..64b7f5a --- /dev/null +++ b/FRouter/FRouter.dart @@ -0,0 +1,328 @@ +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; + +class FRouter extends StatefulWidget { + // 是否是首页 默认为非首页 + bool isFirstPage; + + // 是否显示AppBar + bool isShowAppBar; + + Widget child; + String title; + ThemeData theme; + ThemeData darkTheme; + Color color; + GlobalKey navigatorKey; + GenerateAppTitle onGenerateTitle; + + // 路由集合 所有的路由跳转都放在这里集中管理 + Map routes; + ThemeMode themeMode; + + // 默认初始路由 + String initialRoute = '/'; + RouteFactory onGenerateRoute; + RouteFactory onUnknownRoute; + List navigatorObservers; + TransitionBuilder builder; + Locale locale; + Iterable> localizationsDelegates; + LocaleListResolutionCallback localeListResolutionCallback; + LocaleResolutionCallback localeResolutionCallback; + Iterable supportedLocales; + bool debugShowMaterialGrid; + bool showPerformanceOverlay; + bool checkerboardRasterCacheImages; + bool checkerboardOffscreenLayers; + bool showSemanticsDebugger; + bool debugShowCheckedModeBanner; + + // AppBar有关 + Widget appBarleading; + bool automaticallyImplyLeading; + Widget appBarTitle; + List appBarActions; + Widget appBarFlexibleSpace; + PreferredSizeWidget appBarBottom; + double appBarElevation; + ShapeBorder appBarShape; + Color appBarBackgroundColor; + Brightness appBarBrightness; + IconThemeData appBarIconTheme; + IconThemeData appBarActionsIconTheme; + TextTheme appBarTextTheme; + bool appBarPrimary; + bool appBarCenterTitle; + double appBarTitleSpacing = NavigationToolbar.kMiddleSpacing; + double appBarToolbarOpacity; + double appBarBottomOpacity; + + // Scaffod有关 + Widget body; + Widget floatingActionButton; + FloatingActionButtonLocation floatingActionButtonLocation; + FloatingActionButtonAnimator floatingActionButtonAnimator; + List persistentFooterButtons; + Widget drawer; + Widget endDrawer; + Color drawerScrimColor; + double drawerEdgeDragWidth; + DragStartBehavior drawerDragStartBehavior; + Color backgroundColor; + Widget bottomNavigationBar; + Widget bottomSheet; + bool resizeToAvoidBottomPadding; + bool resizeToAvoidBottomInset; + bool primary; + + bool extendBody; + + FRouter({ + Key key, + this.isFirstPage = false, + this.isShowAppBar = false, + this.child, + this.title = '', + this.theme, + this.darkTheme, + this.themeMode = ThemeMode.system, + this.color, + // 路由有关 + this.navigatorKey, + this.onGenerateTitle, + this.routes = const {}, + this.initialRoute, + this.onGenerateRoute, + this.onUnknownRoute, + this.navigatorObservers = const [], + this.builder, + // 本地化有关 + this.locale, + this.localizationsDelegates, + this.localeListResolutionCallback, + this.localeResolutionCallback, + this.supportedLocales = const [Locale('en', 'US')], + // debug有关 + this.debugShowMaterialGrid = false, + this.showPerformanceOverlay = false, + this.checkerboardRasterCacheImages = false, + this.checkerboardOffscreenLayers = false, + this.showSemanticsDebugger = false, + this.debugShowCheckedModeBanner = true, + + // AppBar有关 + this.appBarleading, + this.automaticallyImplyLeading = true, + this.appBarTitle, + this.appBarActions, + this.appBarFlexibleSpace, + this.appBarBottom, + this.appBarElevation, + this.appBarShape, + this.appBarBackgroundColor, + this.appBarBrightness, + this.appBarIconTheme, + this.appBarActionsIconTheme, + this.appBarTextTheme, + this.appBarPrimary = true, + this.appBarCenterTitle, + this.appBarTitleSpacing = NavigationToolbar.kMiddleSpacing, + this.appBarToolbarOpacity = 1.0, + this.appBarBottomOpacity = 1.0, + + // Scaffod有关 + this.floatingActionButton, + this.floatingActionButtonLocation, + this.floatingActionButtonAnimator, + this.persistentFooterButtons, + this.drawer, + this.endDrawer, + this.bottomNavigationBar, + this.bottomSheet, + this.backgroundColor, + this.resizeToAvoidBottomPadding, + this.resizeToAvoidBottomInset, + this.primary = true, + this.drawerDragStartBehavior = DragStartBehavior.start, + this.extendBody = false, + this.drawerScrimColor, + this.drawerEdgeDragWidth, + }) : assert(isFirstPage != null), + assert(isShowAppBar != null), + // MaterialApp 有关 + assert(routes != null), + assert(navigatorObservers != null), + assert(title != null), + assert(debugShowMaterialGrid != null), + assert(showPerformanceOverlay != null), + assert(checkerboardRasterCacheImages != null), + assert(checkerboardOffscreenLayers != null), + assert(showSemanticsDebugger != null), + assert(debugShowCheckedModeBanner != null), + // appbar有关 + assert(automaticallyImplyLeading != null), + assert(appBarElevation == null || appBarElevation >= 0.0), + assert(appBarPrimary != null), + assert(appBarTitleSpacing != null), + assert(appBarToolbarOpacity != null), + assert(appBarBottomOpacity != null), + // Scaffold 有关 + assert(primary != null), + assert(extendBody != null), + assert(drawerDragStartBehavior != null), + super(key: key); + + @override + FRouterState createState() => FRouterState(); + + /// 发送路由到新页面 + static sendRouterPage(BuildContext context, Widget page) { + Navigator.of(context) + .push(MaterialPageRoute(builder: (BuildContext context) { + return page; + })); + } + + /// 发送命名路由 这个需要配合 [routes] 属性使用 + static sendRouter(BuildContext context, String routeName) { + Navigator.of(context).pushNamed(routeName); + } + + get getDatas => routes; + + set setDatas(Map datas) => datas = routes; + + /// 返回上个页面的路由 参数2:要传递给上个页面的数据 + static backPageRouter(BuildContext context, {T backData}) { + Navigator.of(context).pop(backData); + } + + /// 接收路由返回的数据 参数2:路由名称 + Future receiverRouterData( + BuildContext context, String routeName) async { + var data = await Navigator.of(context).pushNamed(routeName); + return data; + } +} + +class FRouterState extends State { + @override + Widget build(BuildContext context) { + if (widget.isFirstPage == true) { + return MaterialApp( + home: widget.isShowAppBar == true + ? Scaffold( + appBar: AppBar( + key: widget.key, + leading: widget.appBarleading, + automaticallyImplyLeading: widget.automaticallyImplyLeading, + title: widget.appBarTitle, + actions: widget.appBarActions, + flexibleSpace: widget.appBarFlexibleSpace, + bottom: widget.appBarBottom, + elevation: widget.appBarElevation, + shape: widget.appBarShape, + backgroundColor: widget.appBarBackgroundColor, + brightness: widget.appBarBrightness, + iconTheme: widget.appBarIconTheme, + actionsIconTheme: widget.appBarActionsIconTheme, + textTheme: widget.appBarTextTheme, + primary: widget.appBarPrimary, + centerTitle: widget.appBarCenterTitle, + titleSpacing: widget.appBarTitleSpacing, + toolbarOpacity: widget.appBarToolbarOpacity, + bottomOpacity: widget.appBarBottomOpacity, + ), + body: widget.body, + floatingActionButton: widget.floatingActionButton, + floatingActionButtonLocation: + widget.floatingActionButtonLocation, + floatingActionButtonAnimator: + widget.floatingActionButtonAnimator, + persistentFooterButtons: widget.persistentFooterButtons, + drawer: widget.drawer, + endDrawer: widget.endDrawer, + bottomNavigationBar: widget.bottomNavigationBar, + bottomSheet: widget.bottomSheet, + backgroundColor: widget.backgroundColor, + resizeToAvoidBottomPadding: widget.resizeToAvoidBottomPadding, + resizeToAvoidBottomInset: widget.resizeToAvoidBottomInset, + primary: widget.primary, + drawerDragStartBehavior: widget.drawerDragStartBehavior, + extendBody: widget.extendBody, + drawerScrimColor: widget.drawerScrimColor, + drawerEdgeDragWidth: widget.drawerEdgeDragWidth, + ) + : widget.child, + title: widget.title, + theme: widget.theme, + darkTheme: widget.darkTheme, + themeMode: widget.themeMode, + color: widget.color, + navigatorKey: widget.navigatorKey, + onGenerateTitle: widget.onGenerateTitle, + routes: widget.routes, + initialRoute: widget.initialRoute, + onGenerateRoute: widget.onGenerateRoute, + onUnknownRoute: widget.onUnknownRoute, + navigatorObservers: widget.navigatorObservers, + builder: widget.builder, + locale: widget.locale, + localizationsDelegates: widget.localizationsDelegates, + localeListResolutionCallback: widget.localeListResolutionCallback, + localeResolutionCallback: widget.localeResolutionCallback, + supportedLocales: widget.supportedLocales, + debugShowMaterialGrid: widget.debugShowMaterialGrid, + showPerformanceOverlay: widget.showPerformanceOverlay, + checkerboardRasterCacheImages: widget.checkerboardRasterCacheImages, + checkerboardOffscreenLayers: widget.checkerboardOffscreenLayers, + showSemanticsDebugger: widget.showSemanticsDebugger, + debugShowCheckedModeBanner: widget.debugShowCheckedModeBanner, + ); + } else { + widget.isShowAppBar == true + ? Scaffold( + appBar: AppBar( + key: widget.key, + leading: widget.appBarleading, + automaticallyImplyLeading: widget.automaticallyImplyLeading, + title: widget.appBarTitle, + actions: widget.appBarActions, + flexibleSpace: widget.appBarFlexibleSpace, + bottom: widget.appBarBottom, + elevation: widget.appBarElevation, + shape: widget.appBarShape, + backgroundColor: widget.appBarBackgroundColor, + brightness: widget.appBarBrightness, + iconTheme: widget.appBarIconTheme, + actionsIconTheme: widget.appBarActionsIconTheme, + textTheme: widget.appBarTextTheme, + primary: widget.appBarPrimary, + centerTitle: widget.appBarCenterTitle, + titleSpacing: widget.appBarTitleSpacing, + toolbarOpacity: widget.appBarToolbarOpacity, + bottomOpacity: widget.appBarBottomOpacity, + ), + body: widget.body, + floatingActionButton: widget.floatingActionButton, + floatingActionButtonLocation: widget.floatingActionButtonLocation, + floatingActionButtonAnimator: widget.floatingActionButtonAnimator, + persistentFooterButtons: widget.persistentFooterButtons, + drawer: widget.drawer, + endDrawer: widget.endDrawer, + bottomNavigationBar: widget.bottomNavigationBar, + bottomSheet: widget.bottomSheet, + backgroundColor: widget.backgroundColor, + resizeToAvoidBottomPadding: widget.resizeToAvoidBottomPadding, + resizeToAvoidBottomInset: widget.resizeToAvoidBottomInset, + primary: widget.primary, + drawerDragStartBehavior: widget.drawerDragStartBehavior, + extendBody: widget.extendBody, + drawerScrimColor: widget.drawerScrimColor, + drawerEdgeDragWidth: widget.drawerEdgeDragWidth, + ) + : widget.child; + } + } +} diff --git a/FRouter/test_frouter.dart b/FRouter/test_frouter.dart new file mode 100644 index 0000000..cd9dbba --- /dev/null +++ b/FRouter/test_frouter.dart @@ -0,0 +1,99 @@ +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'FRouter.dart'; + +void main() => runApp(MainPage()); + +// 使用示例代码 +class MainPage extends StatefulWidget { + @override + MainPageState createState() => new MainPageState(); +} + +class MainPageState extends State { + @override + Widget build(BuildContext context) { + // 首页 isFirstPage: true, + return FRouter( + isFirstPage: true, + isShowAppBar: true, + routes: { + // 不传递数据 + '/pageone': (builder) => PageOne(), + // 传递数据给PageTwo这个页面 + '/pagetwo': (builder) => PageTwo('数据2'), + '/pagethree': (builder) => PageThree('数据3'), + }, + appBarTitle: Text('Hello World'), + child: RaisedButton( + onPressed: () { + // 命名路由 + FRouter.sendRouter(context, '/pageone'); + // 发送路由到新页面 + // FRouter.sendRouterPage(context, PageOne('data')); + }, + child: Text('点击进行跳转'), + ), + ); + } +} + +class PageOne extends StatelessWidget { + + @override + Widget build(BuildContext context) { + // 非首页 isFirstPage: false, 默认就是非首页 + return FRouter( + isShowAppBar: true, + appBarTitle: Text(), + child: RaisedButton( + onPressed: () { + // 返回到上个页面 + FRouter.backPageRouter(context); + }, + child: Text('点击进行跳转'), + ), + ); + } +} + +class PageTwo extends StatelessWidget { + String data; + + PageTwo(this.data); + + @override + Widget build(BuildContext context) { + return FRouter( + isShowAppBar: true, + appBarTitle: Text('PageTwo'), + child: RaisedButton( + onPressed: () { + // 返回数据给上个页面 + FRouter.backPageRouter(context,'返回给上个页面的数据'); + }, + child: Text('点击进行跳转'), + ), + ); + } +} + +class PageThree extends StatelessWidget { + String data; + + PageThree(this.data); + + @override + Widget build(BuildContext context) { + // 不显示AppBar + return FRouter( + isShowAppBar: false, + child: RaisedButton( + onPressed: () { + FRouter.backPageRouter(context); + }, + child: Text('点击进行跳转'), + ), + ); + } +} \ No newline at end of file diff --git a/LICENSE b/LICENSE index 261eeb9..778badf 100644 --- a/LICENSE +++ b/LICENSE @@ -186,7 +186,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright [yyyy] [name of copyright owner] + Copyright [AWeiLoveAndroid] [AWeiLoveAndroid] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/README-EN.md b/README-EN.md new file mode 100644 index 0000000..f98f625 --- /dev/null +++ b/README-EN.md @@ -0,0 +1,147 @@ +# Flutter-learning + +## README + +#### [中文版文档](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/README.md) | [English Docs](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/README-EN.md) + +![logo](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/pics/logo.png?raw=true) + + +# Introductions + +> This library is a collection of Flutter learning resources , summaries, and sample codes. If you want to learn Flutter quickly, check out this library, because this library is very helpful for you. If you like, you can give a `star`. Thank you! Welcome to comment and help improve this library. If you have any questions, please pull issues. + +![](https://img.shields.io/badge/platform-android-lightgreen.svg)![](https://img.shields.io/badge/platform-ios-lightgreen.svg) + +---- + +# Catalog + +## 1、Flutter Resources + +* #### :fire: [Common libraries for Flutter(Everything you want is here)](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/readme/Flutter%E7%9A%84%E9%9C%80%E8%A6%81%E4%B8%8E%E5%8E%9F%E7%94%9F%E4%BA%A4%E4%BA%92%E7%9A%84%E4%B8%80%E4%BA%9B%E5%B8%B8%E7%94%A8%E5%BA%93/English_docs/Common%20libraries%20for%20Flutter.md) + +* #### [Flutter basis](https://www.jianshu.com/p/2c9867e737a1) + +* #### [Flutter tools,install and wtf problems](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/readme/Flutter%E4%BB%8E%E9%85%8D%E7%BD%AE%E5%AE%89%E8%A3%85%E5%88%B0%E5%A1%AB%E5%9D%91%E6%8C%87%E5%8D%97%E8%AF%A6%E8%A7%A3.md) + + +* #### :+1: [Flutter code template plugin for Android Studio, IDEA & VSCode](https://github.com/AweiLoveAndroid/Flutter-learning/tree/master/code_plugins) + +* #### [Dart languages](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/readme/Dart%E8%AF%AD%E6%B3%95.md) + +* #### [Flutter widgets VS Android widgets](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/readme/Flutter%E5%92%8C%E5%8E%9F%E7%94%9FAndroid%E6%8E%A7%E4%BB%B6%E5%AF%B9%E6%AF%94.md) + +* #### [Flutter widgets VS react native widgets](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/readme/Flutter%E5%92%8Creact%20native%E7%9A%84%E5%AF%B9%E6%AF%94.md) + +* #### [Commands of yarn,nodejs,npm & Flutter](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/readme/yarn%EF%BC%8Cnodejs%EF%BC%8Cnpm%EF%BC%8CFlutter%E6%9C%89%E5%85%B3%E5%91%BD%E4%BB%A4.md) + +* #### [Flutter Chinese Website, written by me(Imitate flutter.io)](https://github.com/AweiLoveAndroid/FlutterWebsiteCN_Mine) + +---- + + +## 2、Sample codes and projects + + +* #### [Flutter demo codes](https://github.com/AweiLoveAndroid/Flutter-learning/tree/master/projects/flutter-demo) + + +* #### [Dart grammar codes](https://github.com/AweiLoveAndroid/Flutter-learning/tree/master/projects/dart_demo/test) + +* #### [Tools -- FractionalOffsetUtil.dart](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/projects/flutter-demo/util/FractionalOffsetUtil.dart) + +---- + + +## 3、Flutter documents + +* #### [Flutter translation](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/flutter-learning-doc-resources/%E5%AE%98%E6%96%B9%E6%96%87%E6%A1%A3%E8%AF%91%E6%96%87/Android%E5%BC%80%E5%8F%91%E8%80%85%E5%8F%82%E8%80%83.md) + +* #### [Flutter blogs](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/flutter-learning-doc-resources/Flutter%E6%9C%89%E5%85%B3%E5%8D%9A%E5%AE%A2%E8%AE%B2%E8%A7%A3.md) + +* #### Comparison of Flutter and other platforms + + * ##### [Flutter for Android developers](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/flutter-learning-doc-resources/%E5%AE%98%E6%96%B9%E6%96%87%E6%A1%A3%E8%AF%91%E6%96%87/Android%E5%BC%80%E5%8F%91%E8%80%85%E5%8F%82%E8%80%83.md) + + * ##### [Flutter for Android developers]() + + * ##### [Flutter for React Native developers]() + +---- + + +## 4、Websites for Flutter & Dart + +### ★ About Flutter Websites + +##### :arrow_right: [Flutter Website https://flutter.dev/docs/](https://flutter.dev/docs/) + Official website,English language. + +##### :arrow_right: [Flutter Chinese official website https://flutter-io.cn/](https://flutter-io.cn/) + It's new, you can find videos,blogs,docs & codelabs in it.It is very comprehensive. + + +##### :arrow_right: [http://www.flutterj.com/](http://www.flutterj.com/) + Flutter website for develops. + +##### :arrow_right: [Flutter Github : https://github.com/flutter/flutter(https://github.com/flutter/flutter) + Flutter open source code,you can find sources and samples form github. + +### ★ About Dart Websites + +##### :arrow_right: Dart Open source code libraries: [https://pub.dev](https://pub.dev) + You can download Dart libraries here.Also You can upload open source library to `https://pub.dev`. + + +##### :arrow_right: Dart website: [https://dart.dev](https://dart.dev) + Official website,English language. + +##### :arrow_right: dart-pad Github: [https://github.com/dart-lang/dart-pad](https://github.com/dart-lang/dart-pad) + Source code for the online editor for the Dart language. + +##### :arrow_right: DartPad online editor: [https://dartpad.dartlang.org/](https://dartpad.dartlang.org/) + Dart language online editor + +---- + +# Donation + +> If this library is very helpful to you, you are willing to support the further development of this project and the continuous maintenance of this project. You can scan the following QR code, let me have a cup of coffee or beer. Thank you very much for your donation. Thank you! + +![donation](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/pics/donation.png?raw=true) + +---- + + +# About me + +### ● Wechat: + +> Search `wei_xing_tian_xia` and add me. + +### ● Wechat public account : + +Search `Flutter那些事` and follow me. For further information, please scan the QR code below to follow us. + +![Wechat public account](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/pics/%E5%85%AC%E4%BC%97%E5%8F%B7%E4%BA%8C%E7%BB%B4%E7%A0%81.jpg?raw=true) + +---- + +# Licence + +``` +Copyright 2018,AWeiLoveAndroid,阿韦 + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +``` diff --git a/README.md b/README.md index 6cbfbf5..4c409ae 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,15 @@ # Flutter-learning +## README + +#### [中文版文档](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/README.md) | [English Docs](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/README-EN.md) + +![logo](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/pics/logo.png?raw=true) + + # 介绍 -> 这个库主要是一些Flutter学习资料,个人总结,项目示例代码。如果你想快速学习Flutter,欢迎查看这个库,对你很有帮助的。喜欢的话就给个`Star`,谢谢。欢迎大家多提意见,帮忙完善这个库。如果有问题,欢迎提issue +> 这个库主要是一些Flutter学习资料,个人总结,项目示例代码。如果你想快速学习Flutter,欢迎查看这个库,对你很有帮助的。喜欢的话就给个`Star`,谢谢。欢迎大家多提意见,帮忙完善这个库。如果有问题,欢迎提issue。**想与我联系请看文档最后的联系方式。感谢大家支持!** ---- @@ -10,15 +17,17 @@ ## 一、自己总结的Flutter有关资料 +* #### :fire: [Flutter的需要与原生交互的一些常用库](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/readme/Flutter%E7%9A%84%E9%9C%80%E8%A6%81%E4%B8%8E%E5%8E%9F%E7%94%9F%E4%BA%A4%E4%BA%92%E7%9A%84%E4%B8%80%E4%BA%9B%E5%B8%B8%E7%94%A8%E5%BA%93/Flutter%E7%9A%84%E9%9C%80%E8%A6%81%E4%B8%8E%E5%8E%9F%E7%94%9F%E4%BA%A4%E4%BA%92%E7%9A%84%E4%B8%80%E4%BA%9B%E5%B8%B8%E7%94%A8%E5%BA%93.md) + * #### [Flutter基础全面详解](https://www.jianshu.com/p/2c9867e737a1) * #### [Flutter从配置安装到填坑指南详解](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/readme/Flutter%E4%BB%8E%E9%85%8D%E7%BD%AE%E5%AE%89%E8%A3%85%E5%88%B0%E5%A1%AB%E5%9D%91%E6%8C%87%E5%8D%97%E8%AF%A6%E8%A7%A3.md) -* #### [Flutter和原生Android控件对比](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/readme/Flutter%E5%92%8C%E5%8E%9F%E7%94%9FAndroid%E6%8E%A7%E4%BB%B6%E5%AF%B9%E6%AF%94.md) +* #### :+1: [Flutter代码模板插件,适用于AS以及IDEA 以及VSCode](https://github.com/AweiLoveAndroid/Flutter-learning/tree/master/code_plugins) * #### [Dart语法](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/readme/Dart%E8%AF%AD%E6%B3%95.md) -* #### [Flutter的需要与原生交互的一些常用库](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/readme/Flutter%E7%9A%84%E9%9C%80%E8%A6%81%E4%B8%8E%E5%8E%9F%E7%94%9F%E4%BA%A4%E4%BA%92%E7%9A%84%E4%B8%80%E4%BA%9B%E5%B8%B8%E7%94%A8%E5%BA%93.md) +* #### [Flutter和原生Android控件对比](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/readme/Flutter%E5%92%8C%E5%8E%9F%E7%94%9FAndroid%E6%8E%A7%E4%BB%B6%E5%AF%B9%E6%AF%94.md) * #### [Flutter和react native的对比](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/readme/Flutter%E5%92%8Creact%20native%E7%9A%84%E5%AF%B9%E6%AF%94.md) @@ -26,20 +35,55 @@ * #### [我模仿Flutter中文官网写的一个本地的html页面,同时将官网的一些**未翻译的英文**页面**翻译**成了中文。](https://github.com/AweiLoveAndroid/FlutterWebsiteCN_Mine) -* #### :+1: [Flutter代码模板插件,适用于AS以及IDEA](https://github.com/AweiLoveAndroid/Flutter-learning/tree/master/code_plugins) -## 二、相关示例代码和项目实战 +---- + + +## 二、Flutter原创干货视频 + +#### :fire: :movie_camera: [Flutter基础快速入门全攻略](https://edu.csdn.net/course/detail/26227) +从开发实践中得来的经验和教训,全部免费赠送给大家。示例都是开发中用到的,结合具体案例做基础知识讲解,作者讲解的细致好懂,思路清晰,作者课后答疑解惑耐心仔细,帮助了很多开发者,难得一遇的良心讲师。 + -* #### [Flutter相关demo示例代码](https://github.com/AweiLoveAndroid/Flutter-learning/tree/master/projects/flutter-demo) +#### :fire: :movie_camera: [Flutter实战网易新闻APP](https://edu.csdn.net/course/detail/26858) +你不成长,就会被淘汰;你不学习新知识,就会被陈旧的不符合发展趋势的技术耽误自己的前途。那么问题来了,如今跨平台技术那么火爆,Flutter又是最牛逼全面的一个技术,难道你想眼睁睁被社会无情淘汰吗?我是阿韦,年薪50W大佬教你如何快速掌握Flutter精髓,独家秘笈传给大家,市面上找不到的独家精华全部奉献给大家, 只为企业需求量身打造,让你学完无缝衔接企业需求上手项目开发,免费赠送Flutter面试指导和一对一答疑解惑,切实解决你的燃眉之急,让你学好Flutter,能够使用Flutter进行项目开发,升职加薪不再是梦。 -* #### [Dart语法详解相关示例代码](https://github.com/AweiLoveAndroid/Flutter-learning/tree/master/projects/dart_demo/test) +#### :fire: :movie_camera: [Flutter从基础到实践全套视频](https://edu.csdn.net/combo/detail/1533) +本套餐包含入门+进阶实战课程,免费赠送Flutter基础课程,从简到难、从浅入深,逐步带领大家了解Flutter,熟悉掌握Flutter的组成部分,最后以一个完整的仿网易新闻的UI实战讲解,教会大家如何合理选择UI组件,并且使用组件快速实现我们的需求,完成一个完整的Flutter项目,让你学完即可进入企业项目实践。 + + +---- + +## 三、相关示例代码和项目实战 + +* #### :fire: [Flutter相关demo示例代码](https://github.com/AweiLoveAndroid/Flutter-learning/tree/master/projects/flutter-demo) + + +* #### :fire: [Dart语法详解相关示例代码](https://github.com/AweiLoveAndroid/Flutter-learning/tree/master/projects/dart_demo/test) * #### [自己封装的一个线性渐变工具类FractionalOffsetUtil.dart](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/projects/flutter-demo/util/FractionalOffsetUtil.dart) -## 三、Flutter相关学习文档 -* #### [Flutter相关译文](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/flutter-learning-doc-resources/Flutter%E7%9B%B8%E5%85%B3%E8%AF%91%E6%96%87.md) +---- + +## 四、本人的开源框架和插件库 + +* #### :fire: [自己写的轻量级路由框架 FRouter,让路由使用和书写更容易,更好处理和维护。值得关注一下。](https://github.com/AweiLoveAndroid/Flutter-learning/tree/master/FRouter) + +* #### :+1: [友盟统计Flutter插件](https://github.com/AweiLoveAndroid/umeng_analytics_flutter) + +* #### :+1: [Flutter调用Android的电量和判断是否充电插件](https://github.com/AweiLoveAndroid/flutter_os) + +* #### :+1: [Flutter获取Android设备信息插件](https://github.com/AweiLoveAndroid/flutter_device_information) + +* #### :+1: [Flutter常用的工具类](https://github.com/AweiLoveAndroid/FlutterUtil) + +---- + +## 五、Flutter相关学习文档 + +* #### [Flutter相关译文](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/flutter-learning-doc-resources/%E5%AE%98%E6%96%B9%E6%96%87%E6%A1%A3%E8%AF%91%E6%96%87/Android%E5%BC%80%E5%8F%91%E8%80%85%E5%8F%82%E8%80%83.md) * #### [Flutter有关博客详解](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/flutter-learning-doc-resources/Flutter%E6%9C%89%E5%85%B3%E5%8D%9A%E5%AE%A2%E8%AE%B2%E8%A7%A3.md) @@ -51,33 +95,38 @@ * ##### [Flutter和React Native的对比]() -## 四、Flutter、Dart有关网站 +---- -#### ★ Flutter有关网站 +## 六、Flutter、Dart有关网站 -##### :arrow_right: [Flutter官方文档 https://flutter.io/docs/](https://flutter.io/docs/) 官方主页,英文版。 +### ★ Flutter有关网站 -##### :arrow_right: [Flutter中文版 http://doc.flutter-dev.cn/](http://doc.flutter-dev.cn/) 网友自制的中文网,翻译更新的比较快,基本跟官网同步,但是翻译的只有一部分。 +##### :arrow_right: [Flutter官方文档 https://flutter.io/docs/](https://flutter.io/docs/) +官方主页,英文版。 -##### :arrow_right: [Flutter中文网 https://flutterchina.club/](https://flutterchina.club/) 网友自制的中文网,内容翻译的比较多,但是内容还比较老,还没来得及更新最新内容。 +##### :arrow_right: [Flutter中文官网 https://flutter-io.cn/](https://flutter-io.cn/) +官方的中文网,最新出来的,资料齐全,视频、博客、文档、最新咨询都有。 -##### :arrow_right: [Flutter中文官网 https://flutter-io.cn/](https://flutter-io.cn/) 官方的中文网,最新出来的,资料齐全,视频、博客、文档、最新咨询都有。 -##### :arrow_right: [Flutter Github地址 https://github.com/flutter/flutter](https://github.com/flutter/flutter) +##### :arrow_right: [Flutter教程]http://www.flutterj.com/) -#### ★ Dart有关网站 -##### :arrow_right: [开源代码下载库 https://pub.dartlang.org/](https://pub.dartlang.org/) 三方库都可以在这里下载。 +##### :arrow_right: [Flutter Github地址 https://github.com/flutter/flutter](https://github.com/flutter/flutter) +Flutter开源库,上面有源码和示例项目。 -##### :arrow_right: [Dart语言官方主页 https://www.dartlang.org/](https://www.dartlang.org/) 官方主页,英文版。 +### ★ Dart有关网站 -##### :arrow_right: [国内最大的Dart语言中文社区 http://www.cndartlang.com/](http://www.cndartlang.com/) 这个网站有Flutter和Dart的学习资料,很全面。 +##### :arrow_right: [开源代码下载库 https://pub.dartlang.org/](https://pub.dartlang.org/) +三方库都可以在这里下载。 -##### :arrow_right: [Dart中文主页 https://www.dart-china.org/](https://www.dart-china.org/) Dart语言中文社区。 +##### :arrow_right: [Dart语言官方主页 https://www.dartlang.org/](https://www.dartlang.org/) +官方主页,英文版。 -##### :arrow_right: [dart-pad Github地址 https://github.com/dart-lang/dart-pad](https://github.com/dart-lang/dart-pad) Dart语言的在线编辑器的源码。 +##### :arrow_right: [dart-pad Github地址 https://github.com/dart-lang/dart-pad](https://github.com/dart-lang/dart-pad) +Dart语言的在线编辑器的源码。 -##### :arrow_right: [DartPad在线编辑器 https://dartpad.dartlang.org/](https://dartpad.dartlang.org/) Dart语言的在线编辑器 +##### :arrow_right: [DartPad在线编辑器 https://dartpad.dartlang.org/](https://dartpad.dartlang.org/) +Dart语言的在线编辑器 ---- @@ -87,6 +136,34 @@ ![赞赏](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/pics/donation.png?raw=true) +---- + +# 联系我 + +### ● 微信: + +> 欢迎关注我的微信:`wei_xing_tian_xia` + +### ● 微信群: + +> 由于大家学习热情太高,**微信群目前不能扫码加入了,麻烦大家想进微信群的朋友们,加我微信拉你进群。** + +### ● 微信公众号: + +> 我的微信公众号也开通了,欢迎大家关注:`Flutter那些事`,扫码就可以关注了,专注于研究Flutter的公众号,最新最全面的系统的Flutter干货总结都在这个公众号,欢迎关注。 + +![我的微信公众号](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/pics/%E5%85%AC%E4%BC%97%E5%8F%B7%E4%BA%8C%E7%BB%B4%E7%A0%81.jpg?raw=true) + + +### ● QQ群: + +> 2千人QQ群,**Flutter学习开发交流群,QQ群号:695025386**, 欢迎大家加入。 + +### ● 个人博客: + +[简书博客 AWeiLoveAndroid](https://www.jianshu.com/u/f408bdadacce) + +[掘金博客 AWeiLoveAndroid](https://juejin.im/user/5a07c6c0f265da430a501017) ---- diff --git a/code_plugins/README-CN.md b/code_plugins/README-CN.md new file mode 100644 index 0000000..7636ee5 --- /dev/null +++ b/code_plugins/README-CN.md @@ -0,0 +1,13 @@ +# 使用说明 + +### ▶【提示:】更多详细的图文使用详细讲解,请看我的博客:[Flutter代码模板,解放双手,提高开发效率必备](https://www.jianshu.com/p/4184745d6983) + + +> 导入到Android Studio 或者 Intellij IDEA + +**Tips: 如果你不喜欢 `new`关键字, 你可以下载 [no_new_keywords/settings.jar](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/code_plugins/no_new_keywords/settings.jar) 文件, 否则请下载 [have_new_keywords/settings.jar](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/code_plugins/have_new_keywords/settings.jar) 这个文件。** + + +> 导入到VSCode + +**Tips: 如果你不喜欢 `new`关键字, 你可以下载 [no_new_keywords/dart.json](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/code_plugins/no_new_keywords/dart.json) 文件, 否则请下载 [have_new_keywords/dart.json](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/code_plugins/have_new_keywords/dart.json) 这个文件。** \ No newline at end of file diff --git a/code_plugins/have_new_keywords/dart.json b/code_plugins/have_new_keywords/dart.json new file mode 100644 index 0000000..079393d --- /dev/null +++ b/code_plugins/have_new_keywords/dart.json @@ -0,0 +1,648 @@ +{ + // Place your snippets for dart here. Each snippet is defined under a snippet name and has a prefix, body and + // description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are: + // $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the + // same ids are connected. + // Example: + // "Print to console": { + // "prefix": "log", + // "body": [ + // "console.log('$1');", + // "$2" + // ], + // "description": "Log output to console" + // }, + + "创建AnimatedBuilder": { + "prefix": "bab", + "body": [ + "new AnimatedBuilder(", + " animation: $1,", + " child: $1,", + " builder: (BuildContext context, Widget child) {", + " return Container();", + " },", + "),", + ], + "description": "创建AnimatedBuilder" + }, + "创建Build()方法": { + "prefix": "bu", + "body": [ + "@override", + "Widget build(BuildContext context) {", + " return $1;", + "}", + ], + "description": "创建Build()方法" + }, + "创建FutureBuilder": { + "prefix": "bufb", + "body": [ + "new FutureBuilder(", + " future: $1,", + " initialData: $1,", + " builder: (BuildContext context, AsyncSnapshot snapshot) {", + " return $1;", + " },", + ");", + ], + "description": "创建FutureBuilder" + }, + "创建LayoutBuilder": { + "prefix": "bulb", + "body": [ + "new LayoutBuilder(", + " builder: (BuildContext context, BoxConstraints constraints) {", + " return $1;", + " },", + ");", + ], + "description": "创建LayoutBuilder" + }, + "创建OrientationBuilder": { + "prefix": "buob", + "body": [ + "new OrientationBuilder(", + " builder: (BuildContext context, Orientation orientation) {", + " return Container();", + " },", + ");", + ], + "description": "创建OrientationBuilder" + }, + "创建StatefulBuilder": { + "prefix": "bustf", + "body": [ + "new StatefulBuilder(", + " builder: (BuildContext context, setState) {", + " return $1;", + " },", + ");", + ], + "description": "创建StatefulBuilder" + }, + "创建StreamBuilder": { + "prefix": "bustr", + "body": [ + "new StreamBuilder(", + " stream: $1,", + " initialData: $2,", + " builder: (BuildContext context, AsyncSnapshot snapshot) {", + " return $3;", + " },", + ");", + ], + "description": "创建StreamBuilder" + }, + "自定义CustomClipper": { + "prefix": "cc", + "body": [ + "class $1 extends CustomClipper {", + " @override", + " Path getClip(Size size) {", + " //TODO:", + " }", + "", + " @override", + " bool shouldReclip(CustomClipper oldClipper) => false;", + "}", + ], + "description": "自定义CustomClipper" + }, + "创建Center": { + "prefix": "cen", + "body": [ + "new Center(", + " child: $1," , + "),", + ], + "description": "创建Center" + }, + "创建Column": { + "prefix": "col", + "body": [ + "new Column(", + " chilchildren: [$1]," , + "),", + ], + "description": "创建Column" + }, + "创建完整的Container": { + "prefix": "con", + "body": [ + "new Container(", + " //宽度", + " width: $1,", + " //高度", + " height: $2,", + " // 盒子样式", + " decoration: new BoxDecoration(", + " color: Colors.$3,", + " //设置Border属性给容器添加边框", + " border: new Border.all(", + " //为边框添加颜色", + " color: Colors.$3,", + " width: $4, //边框宽度", + " ),", + " ),", + " child: $5,", + ");", + ], + "description": "创建完整的Container" + }, + "自定义CustomPainter": { + "prefix": "cp", + "body": [ + "class $1Painter extends CustomPainter {", + " @override", + " void paint(Canvas canvas, Size size) {", + " //TODO", + " }", + "", + " @override", + " bool shouldRepaint($name$Painter oldDelegate) => false;", + "", + " @override", + " bool shouldRebuildSemantics($1Painter oldDelegate) => false;", + "}", + ], + "description": "自定义CustomPainter" + }, + "CustomScrollView + SliverPadding创建列表,子控件带有边距": { + "prefix": "csv", + "body": [ + "new CustomScrollView(", + " shrinkWrap: true,", + " slivers: [", + " new SliverPadding(", + " padding: const EdgeInsets.all($1),", + " sliver: new SliverList(", + " delegate: new SliverChildListDelegate(", + " [", + " //TODO:请填写子控件", + " ],", + " ),", + " ),", + " ),", + " ],", + ");", + ], + "description": "CustomScrollView + SliverPadding创建列表,子控件带有边距" + }, + "使用CustomScrollView + SliverGrid创建列表": { + "prefix": "csv2", + "body": [ + "new CustomScrollView(", + " shrinkWrap: true,", + " slivers: [", + " new SliverGrid(", + " // 设置grid的宽高、间距属性", + " gridDelegate: new SliverGridDelegateWithMaxCrossAxisExtent(", + " // 可以理解为:每一个item的宽(或高)的最大值", + " maxCrossAxisExtent: $maxCrossAxisExtent$,", + " // 行之间的间距", + " mainAxisSpacing: $1,", + " // 列之间的间距", + " crossAxisSpacing: $2,", + " // 子孩子的宽高比例,即:宽度/高度的值", + " childAspectRatio: $3,", + " ),", + " // 设置每一个item的布局", + " delegate: new SliverChildBuilderDelegate(", + " (BuildContext context, int index) {", + " return $4;", + " },", + " childCount: $5,", + " ),", + " )", + " ],", + ");", + ], + "description": "使用CustomScrollView + SliverGrid创建列表" + }, + "创建GridView.count": { + "prefix": "gv", + "body": [ + "new GridView.count(", + " // 创建几列", + " crossAxisCount: $1,", + " // Axis.horizontal表示横向滑动,scrollDirection: Axis.vertical表示纵向滑动", + " scrollDirection: Axis.vertical,", + " // 列之间的间距", + " crossAxisSpacing: $2,", + " // 行之间的间距", + " mainAxisSpacing: $3,", + " // 默认false 是否根据子孩子的宽高自动包裹item自身", + " shrinkWrap: false,", + " // true表示数据倒序排列 false表示顺序排列", + " reverse: false,", + " // 子孩子的比例", + " childAspectRatio: $4,", + " // 设置子孩子item,这里传入子孩子控件", + " children: $5,", + ");", + ], + "description": "创建GridView.count" + }, + "创建 Inherited": { + "prefix": "inh", + "body": [ + "class $1 extends InheritedWidget {", + " $1({Key key, this.child}) : super(key: key, child: child);", + "", + " final Widget child;", + "", + " static $1 of(BuildContext context) {", + " return (context.inheritFromWidgetOfExactType($1)as $1);", + " }", + "", + " @override", + " bool updateShouldNotify( $1 oldWidget) {", + " return true;", + " }", + "}", + ], + "description": "创建 Inherited" + }, + "创建基本的ListView": { + "prefix": "lv", + "body": [ + "new ListView(", + " children: [", + " //TODO:这里写子控件。", + " ],", + ");", + ], + "description": "创建基本的ListView" + }, + "创建ListView.builder": { + "prefix": "lvb", + "body": [ + "new ListView.builder(", + " padding: new EdgeInsets.all($value$),", + " itemCount: $itemCount$,", + " itemBuilder: (BuildContext context, int index) {", + " return $widget$;", + " },", + ");", + ], + "description": "创建ListView.builder" + }, + "创建带分割线的ListView": { + "prefix": "lvd", + "body": [ + "new ListView(", + " shrinkWrap: true,", + " // 排列方向,Axis.horizontal表示水平,Axis.vertical表示垂直", + " scrollDirection: Axis.vertical,", + " padding: const EdgeInsets.all(20.0),", + " children: [", + " $1,", + " new Divider(height: 1.0, color: Colors.grey),", + " $1,", + " new Divider(height: 1.0, color: Colors.grey),", + " // todo: 建议控件多的话可以做一个封装", + " ],", + ");", + ], + "description": "创建带分割线的ListView" + }, + "创建RadioListTile,可以单选的item": { + "prefix": "lvr", + "body": [ + " //TODO:以下代码要写在State类里面", + " Widget items() {", + " return new Column(", + " // In the build function of that State", + " children: [", + " new RadioListTile(", + " title: const Text('$1'),", + " value: SingingCharacter.title1,", + " groupValue: _character,", + " onChanged: (SingingCharacter value) {", + " setState(() {", + " _character = value;", + " });", + " },", + " ),", + " new RadioListTile(", + " title: const Text('$2'),", + " value: SingingCharacter.title2,", + " groupValue: _character,", + " onChanged: (SingingCharacter value) {", + " setState(() {", + " _character = value;", + " });", + " },", + " ),", + " ],", + " );", + " }", + "", + " // In the State of a stateful widget:", + " SingingCharacter _character = SingingCharacter.title1;", + "", + "// TODO: 这个类写在State类外面", + "enum SingingCharacter { title1, title2 }", + ], + "description": "创建RadioListTile,可以单选的item" + }, + "创建带有各种ListTile的ListView": { + "prefix": "lvt", + "body": [ + "new ListView(", + " children: [", + " // 一个有图片和文字组成的简单列表item", + " new ListTile(", + " leading: new Icon(Icons.$1),", + " title: new Text('$title$'),", + " subtitle: new Text('$2'),", + " // 右边的图标", + " trailing: new Icon(Icons.$1),", + " onTap: () {", + " //TODO:这里处理点击事件", + " },", + " onLongPress: () {", + " //TODO:这里处理长按事件", + " },", + " selected: true,", + " ),", + " // 单选框列表item", + " new CheckboxListTile(", + " value: true,", + " onChanged: ((bool) {", + " //TODO:焦点改变的监听事件写在这里:", + " }),", + " title: new Text('$3'),", + " subtitle: new Text('$4'),", + " selected: true,", + " activeColor: Colors.teal,", + " ),", + " // 开关列表item", + " new SwitchListTile(", + " value: true,", + " onChanged: ((bool) {", + " //TODO:焦点改变的监听事件写在这里:", + " }),", + " title: new Text('$5'),", + " subtitle: new Text('$5'),", + " //如果subtitle文字过长,将会以三行显示", + " isThreeLine: true,", + " selected: true,", + " activeColor: Colors.teal,", + " //SwitchListTile左边的图标", + " secondary: new Icon(Icons.account_circle),", + " ),", + " new AboutListTile(", + " icon: new Icon(Icons.$6),", + " //公司logo", + " applicationIcon: Image.asset('$7'),", + " //app名称", + " applicationName: '关于我们',", + " //app版本号", + " applicationVersion: 'V1.0.0',", + " //版权信息", + " applicationLegalese: '版权归XX科技有限公司所有...',", + " ),", + " ],", + ");", + ], + "description": "创建带有各种ListTile的ListView" + }, + "创建 StatefulWidget 控件": { + "prefix": "mainstf", + "body": [ + "import 'package:flutter/material.dart';", + "", + "void main(){", + "runApp(new MaterialApp(", + " title:'$1',", + " theme: new ThemeData(", + " primarySwatch: Colors.blue,", + "),", + "home: new $2(),", + "));", + "}", + "", + "class $2 extends StatefulWidget{", + "@override", + "_$2State createState() => new _$2State();", + "}", + "", + "class _$2State extends State<$2>{", + "@override", + "Widget build(BuildContext context){", + "return new Scaffold(", + "appBar: new AppBar(", + "title: new Text('$1'),", + "),", + ");", + "}", + "}", + ], + "description": "创建 StatefulWidget 控件" + }, + "创建 StatelessWidget 控件": { + "prefix": "mainstl", + "body": [ + "import 'package:flutter/material.dart';", + "", + "void main(){", + "runApp(new MaterialApp(", + " title:'$1',", + " theme: new ThemeData(", + " primarySwatch: Colors.blue,", + "),", + "home: new $2(),", + "));", + "}", + "", + "class $2 extends StatelessWidget{", + "@override", + "Widget build(BuildContext context){", + "return new Scaffold(", + "appBar: new AppBar(", + "title: new Text('$1'),", + "),", + ");", + "}", + "}", + ], + "description": "创建 StatelessWidget 控件" + }, + "创建方法": { + "prefix": "me", + "body": [ + "void $1(){", + " //TODO", + "}", + ], + "description": "创建方法" + }, + "创建私有方法": { + "prefix": "mep", + "body": [ + "void _$1(){", + " //TODO", + "}", + ], + "description": "创建私有方法" + }, + "创建Row": { + "prefix": "row", + "body": [ + "new Row(", + " children: [],", + "),", + ], + "description": "创建Row" + }, + "创建SizedBox": { + "prefix": "sb", + "body": [ + "new SizedBox(", + " width: $1,", + " height: $2, ", + " child: $3,", + ");", + ], + "description": "创建SizedBox" + }, + "创建SingleChildScrollView": { + "prefix": "ssv", + "body": [ + "SingleChildScrollView(", + " scrollDirection: Axis.vertical,", + " padding: new EdgeInsets.all($1),", + " controller: $2,", + " child: $3,", + ");", + ], + "description": "创建SingleChildScrollView" + }, + "创建Stateful(带有 AnimationController)": { + "prefix": "stanim", + "body": [ + "class $1 extends StatefulWidget {", + " @override", + " _$1State createState() => _$1State();", + "}", + "", + "class _$1State extends State<$1> with SingleTickerProviderStateMixin {", + " AnimationController _controller;", + "", + " @override", + " void initState() {", + " _controller = AnimationController(vsync: this);", + " super.initState();", + " }", + "", + " @override", + " void dispose() {", + " _controller.dispose();", + " super.dispose();", + " }", + " ", + " @override", + " Widget build(BuildContext context) {", + " return Container($2);", + " }", + "}", + ], + "description": "创建Stateful(带有 AnimationController)" + }, + "创建完整的StatefulWidget,包含生命周期相关方法。": { + "prefix": "stf", + "body": [ + "class $1 extends StatefulWidget {", + " @override", + " $1State createState() => new $1State();", + "}", + "", + "class $1State extends State<$1> {", + " @override", + " Widget build(BuildContext context) {", + " return new Scaffold(", + " appBar: new AppBar(", + " title: new Text('$2'),", + " ),", + " );", + " }", + " @override", + " void initState() {", + " // TODO: implement initState", + " super.initState();", + " }", + " ", + " @override", + " void dispose() {", + " // TODO: implement dispose", + " super.dispose();", + " }", + " ", + " @override", + " void didUpdateWidget($1 oldWidget) {", + " // TODO: implement didUpdateWidget", + " super.didUpdateWidget(oldWidget);", + " }", + " ", + " @override", + " void didChangeDependencies() {", + " // TODO: implement didChangeDependencies", + " super.didChangeDependencies();", + " }", + "}", + ], + "description": "创建完整的StatefulWidget,包含生命周期相关方法。" + }, + "创建StatelessWidget": { + "prefix": "stl", + "body": [ + "class $1 extends StatelessWidget {", + " @override", + " Widget build(BuildContext context) {", + " return new Scaffold(", + " appBar: new AppBar(", + " title: new Text('$2'),", + " ),", + " );", + " }", + "}", + ], + "description": "创建StatelessWidget" + }, + + "创建CustomScrollView": { + "prefix": "svc", + "body": [ + "new CustomScrollView(", + " slivers: [", + " //TODO", + " ],", + "),", + ], + "description": "创建CustomScrollView" + }, + + "创建一个标准的Text": { + "prefix": "te", + "body": [ + "new Text('$1',", + " style: new TextStyle(", + " color: Colors.$2, ", + " fontWeight: FontWeight.$3, ", + " fontSize: $4,", + " ),", + " textAlign: TextAlign.$5,", + " textDirection: TextDirection.$6,", + " textScaleFactor: $7,", + " overflow: TextOverflow.$8,", + " locale: Localizations.localeOf(context),", + " maxLines: $9,", + ");", + ], + "description": "创建一个标准的Text" + }, + +} \ No newline at end of file diff --git a/code_plugins/have_new_keywords/settings.jar b/code_plugins/have_new_keywords/settings.jar new file mode 100644 index 0000000..e0edb6f Binary files /dev/null and b/code_plugins/have_new_keywords/settings.jar differ diff --git a/code_plugins/no_new_keywords/dart.json b/code_plugins/no_new_keywords/dart.json new file mode 100644 index 0000000..6bf3fba --- /dev/null +++ b/code_plugins/no_new_keywords/dart.json @@ -0,0 +1,648 @@ +{ + // Place your snippets for dart here. Each snippet is defined under a snippet name and has a prefix, body and + // description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are: + // $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the + // same ids are connected. + // Example: + // "Print to console": { + // "prefix": "log", + // "body": [ + // "console.log('$1');", + // "$2" + // ], + // "description": "Log output to console" + // }, + + "创建AnimatedBuilder": { + "prefix": "bab", + "body": [ + "AnimatedBuilder(", + " animation: $1,", + " child: $1,", + " builder: (BuildContext context, Widget child) {", + " return Container();", + " },", + "),", + ], + "description": "创建AnimatedBuilder" + }, + "创建Build()方法": { + "prefix": "bu", + "body": [ + "@override", + "Widget build(BuildContext context) {", + " return $1;", + "}", + ], + "description": "创建Build()方法" + }, + "创建FutureBuilder": { + "prefix": "bufb", + "body": [ + "FutureBuilder(", + " future: $1,", + " initialData: $1,", + " builder: (BuildContext context, AsyncSnapshot snapshot) {", + " return $1;", + " },", + ");", + ], + "description": "创建FutureBuilder" + }, + "创建LayoutBuilder": { + "prefix": "bulb", + "body": [ + "LayoutBuilder(", + " builder: (BuildContext context, BoxConstraints constraints) {", + " return $1;", + " },", + ");", + ], + "description": "创建LayoutBuilder" + }, + "创建OrientationBuilder": { + "prefix": "buob", + "body": [ + "OrientationBuilder(", + " builder: (BuildContext context, Orientation orientation) {", + " return Container();", + " },", + ");", + ], + "description": "创建OrientationBuilder" + }, + "创建StatefulBuilder": { + "prefix": "bustf", + "body": [ + "StatefulBuilder(", + " builder: (BuildContext context, setState) {", + " return $1;", + " },", + ");", + ], + "description": "创建StatefulBuilder" + }, + "创建StreamBuilder": { + "prefix": "bustr", + "body": [ + "StreamBuilder(", + " stream: $1,", + " initialData: $2,", + " builder: (BuildContext context, AsyncSnapshot snapshot) {", + " return $3;", + " },", + ");", + ], + "description": "创建StreamBuilder" + }, + "自定义CustomClipper": { + "prefix": "cc", + "body": [ + "class $1 extends CustomClipper {", + " @override", + " Path getClip(Size size) {", + " //TODO:", + " }", + "", + " @override", + " bool shouldReclip(CustomClipper oldClipper) => false;", + "}", + ], + "description": "自定义CustomClipper" + }, + "创建Center": { + "prefix": "cen", + "body": [ + "Center(", + " child: $1," , + "),", + ], + "description": "创建Center" + }, + "创建Column": { + "prefix": "col", + "body": [ + "Column(", + " chilchildren: [$1]," , + "),", + ], + "description": "创建Column" + }, + "创建完整的Container": { + "prefix": "con", + "body": [ + "Container(", + " //宽度", + " width: $1,", + " //高度", + " height: $2,", + " // 盒子样式", + " decoration: BoxDecoration(", + " color: Colors.$3,", + " //设置Border属性给容器添加边框", + " border: Border.all(", + " //为边框添加颜色", + " color: Colors.$3,", + " width: $4, //边框宽度", + " ),", + " ),", + " child: $5,", + ");", + ], + "description": "创建完整的Container" + }, + "自定义CustomPainter": { + "prefix": "cp", + "body": [ + "class $1Painter extends CustomPainter {", + " @override", + " void paint(Canvas canvas, Size size) {", + " //TODO", + " }", + "", + " @override", + " bool shouldRepaint($name$Painter oldDelegate) => false;", + "", + " @override", + " bool shouldRebuildSemantics($1Painter oldDelegate) => false;", + "}", + ], + "description": "自定义CustomPainter" + }, + "CustomScrollView + SliverPadding创建列表,子控件带有边距": { + "prefix": "csv", + "body": [ + "CustomScrollView(", + " shrinkWrap: true,", + " slivers: [", + " SliverPadding(", + " padding: const EdgeInsets.all($1),", + " sliver: SliverList(", + " delegate: SliverChildListDelegate(", + " [", + " //TODO:请填写子控件", + " ],", + " ),", + " ),", + " ),", + " ],", + ");", + ], + "description": "CustomScrollView + SliverPadding创建列表,子控件带有边距" + }, + "使用CustomScrollView + SliverGrid创建列表": { + "prefix": "csv2", + "body": [ + "CustomScrollView(", + " shrinkWrap: true,", + " slivers: [", + " SliverGrid(", + " // 设置grid的宽高、间距属性", + " gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(", + " // 可以理解为:每一个item的宽(或高)的最大值", + " maxCrossAxisExtent: $maxCrossAxisExtent$,", + " // 行之间的间距", + " mainAxisSpacing: $1,", + " // 列之间的间距", + " crossAxisSpacing: $2,", + " // 子孩子的宽高比例,即:宽度/高度的值", + " childAspectRatio: $3,", + " ),", + " // 设置每一个item的布局", + " delegate: SliverChildBuilderDelegate(", + " (BuildContext context, int index) {", + " return $4;", + " },", + " childCount: $5,", + " ),", + " )", + " ],", + ");", + ], + "description": "使用CustomScrollView + SliverGrid创建列表" + }, + "创建GridView.count": { + "prefix": "gv", + "body": [ + "GridView.count(", + " // 创建几列", + " crossAxisCount: $1,", + " // Axis.horizontal表示横向滑动,scrollDirection: Axis.vertical表示纵向滑动", + " scrollDirection: Axis.vertical,", + " // 列之间的间距", + " crossAxisSpacing: $2,", + " // 行之间的间距", + " mainAxisSpacing: $3,", + " // 默认false 是否根据子孩子的宽高自动包裹item自身", + " shrinkWrap: false,", + " // true表示数据倒序排列 false表示顺序排列", + " reverse: false,", + " // 子孩子的比例", + " childAspectRatio: $4,", + " // 设置子孩子item,这里传入子孩子控件", + " children: $5,", + ");", + ], + "description": "创建GridView.count" + }, + "创建 Inherited": { + "prefix": "inh", + "body": [ + "class $1 extends InheritedWidget {", + " $1({Key key, this.child}) : super(key: key, child: child);", + "", + " final Widget child;", + "", + " static $1 of(BuildContext context) {", + " return (context.inheritFromWidgetOfExactType($1)as $1);", + " }", + "", + " @override", + " bool updateShouldNotify( $1 oldWidget) {", + " return true;", + " }", + "}", + ], + "description": "创建 Inherited" + }, + "创建基本的ListView": { + "prefix": "lv", + "body": [ + "ListView(", + " children: [", + " //TODO:这里写子控件。", + " ],", + ");", + ], + "description": "创建基本的ListView" + }, + "创建ListView.builder": { + "prefix": "lvb", + "body": [ + "ListView.builder(", + " padding: EdgeInsets.all($value$),", + " itemCount: $itemCount$,", + " itemBuilder: (BuildContext context, int index) {", + " return $widget$;", + " },", + ");", + ], + "description": "创建ListView.builder" + }, + "创建带分割线的ListView": { + "prefix": "lvd", + "body": [ + "ListView(", + " shrinkWrap: true,", + " // 排列方向,Axis.horizontal表示水平,Axis.vertical表示垂直", + " scrollDirection: Axis.vertical,", + " padding: const EdgeInsets.all(20.0),", + " children: [", + " $1,", + " Divider(height: 1.0, color: Colors.grey),", + " $1,", + " Divider(height: 1.0, color: Colors.grey),", + " // todo: 建议控件多的话可以做一个封装", + " ],", + ");", + ], + "description": "创建带分割线的ListView" + }, + "创建RadioListTile,可以单选的item": { + "prefix": "lvr", + "body": [ + " //TODO:以下代码要写在State类里面", + " Widget items() {", + " return Column(", + " // In the build function of that State", + " children: [", + " RadioListTile(", + " title: const Text('$1'),", + " value: SingingCharacter.title1,", + " groupValue: _character,", + " onChanged: (SingingCharacter value) {", + " setState(() {", + " _character = value;", + " });", + " },", + " ),", + " RadioListTile(", + " title: const Text('$2'),", + " value: SingingCharacter.title2,", + " groupValue: _character,", + " onChanged: (SingingCharacter value) {", + " setState(() {", + " _character = value;", + " });", + " },", + " ),", + " ],", + " );", + " }", + "", + " // In the State of a stateful widget:", + " SingingCharacter _character = SingingCharacter.title1;", + "", + "// TODO: 这个类写在State类外面", + "enum SingingCharacter { title1, title2 }", + ], + "description": "创建RadioListTile,可以单选的item" + }, + "创建带有各种ListTile的ListView": { + "prefix": "lvt", + "body": [ + "ListView(", + " children: [", + " // 一个有图片和文字组成的简单列表item", + " ListTile(", + " leading: Icon(Icons.$1),", + " title: Text('$title$'),", + " subtitle: Text('$2'),", + " // 右边的图标", + " trailing: Icon(Icons.$1),", + " onTap: () {", + " //TODO:这里处理点击事件", + " },", + " onLongPress: () {", + " //TODO:这里处理长按事件", + " },", + " selected: true,", + " ),", + " // 单选框列表item", + " CheckboxListTile(", + " value: true,", + " onChanged: ((bool) {", + " //TODO:焦点改变的监听事件写在这里:", + " }),", + " title: Text('$3'),", + " subtitle: Text('$4'),", + " selected: true,", + " activeColor: Colors.teal,", + " ),", + " // 开关列表item", + " SwitchListTile(", + " value: true,", + " onChanged: ((bool) {", + " //TODO:焦点改变的监听事件写在这里:", + " }),", + " title: Text('$5'),", + " subtitle: Text('$5'),", + " //如果subtitle文字过长,将会以三行显示", + " isThreeLine: true,", + " selected: true,", + " activeColor: Colors.teal,", + " //SwitchListTile左边的图标", + " secondary: Icon(Icons.account_circle),", + " ),", + " AboutListTile(", + " icon: Icon(Icons.$6),", + " //公司logo", + " applicationIcon: Image.asset('$7'),", + " //app名称", + " applicationName: '关于我们',", + " //app版本号", + " applicationVersion: 'V1.0.0',", + " //版权信息", + " applicationLegalese: '版权归XX科技有限公司所有...',", + " ),", + " ],", + ");", + ], + "description": "创建带有各种ListTile的ListView" + }, + "创建 StatefulWidget 控件": { + "prefix": "mainstf", + "body": [ + "import 'package:flutter/material.dart';", + "", + "void main(){", + "runApp(MaterialApp(", + " title:'$1',", + " theme: ThemeData(", + " primarySwatch: Colors.blue,", + "),", + "home: $2(),", + "));", + "}", + "", + "class $2 extends StatefulWidget{", + "@override", + "_$2State createState() => _$2State();", + "}", + "", + "class _$2State extends State<$2>{", + "@override", + "Widget build(BuildContext context){", + "return Scaffold(", + "appBar: AppBar(", + "title: Text('$1'),", + "),", + ");", + "}", + "}", + ], + "description": "创建 StatefulWidget 控件" + }, + "创建 StatelessWidget 控件": { + "prefix": "mainstl", + "body": [ + "import 'package:flutter/material.dart';", + "", + "void main(){", + "runApp(MaterialApp(", + " title:'$1',", + " theme: ThemeData(", + " primarySwatch: Colors.blue,", + "),", + "home: $2(),", + "));", + "}", + "", + "class $2 extends StatelessWidget{", + "@override", + "Widget build(BuildContext context){", + "return Scaffold(", + "appBar: AppBar(", + "title: Text('$1'),", + "),", + ");", + "}", + "}", + ], + "description": "创建 StatelessWidget 控件" + }, + "创建方法": { + "prefix": "me", + "body": [ + "void $1(){", + " //TODO", + "}", + ], + "description": "创建方法" + }, + "创建私有方法": { + "prefix": "mep", + "body": [ + "void _$1(){", + " //TODO", + "}", + ], + "description": "创建私有方法" + }, + "创建Row": { + "prefix": "row", + "body": [ + "Row(", + " children: [],", + "),", + ], + "description": "创建Row" + }, + "创建SizedBox": { + "prefix": "sb", + "body": [ + "SizedBox(", + " width: $1,", + " height: $2, ", + " child: $3,", + ");", + ], + "description": "创建SizedBox" + }, + "创建SingleChildScrollView": { + "prefix": "ssv", + "body": [ + "SingleChildScrollView(", + " scrollDirection: Axis.vertical,", + " padding: EdgeInsets.all($1),", + " controller: $2,", + " child: $3,", + ");", + ], + "description": "创建SingleChildScrollView" + }, + "创建Stateful(带有 AnimationController)": { + "prefix": "stanim", + "body": [ + "class $1 extends StatefulWidget {", + " @override", + " _$1State createState() => _$1State();", + "}", + "", + "class _$1State extends State<$1> with SingleTickerProviderStateMixin {", + " AnimationController _controller;", + "", + " @override", + " void initState() {", + " _controller = AnimationController(vsync: this);", + " super.initState();", + " }", + "", + " @override", + " void dispose() {", + " _controller.dispose();", + " super.dispose();", + " }", + " ", + " @override", + " Widget build(BuildContext context) {", + " return Container($2);", + " }", + "}", + ], + "description": "创建Stateful(带有 AnimationController)" + }, + "创建完整的StatefulWidget,包含生命周期相关方法。": { + "prefix": "stf", + "body": [ + "class $1 extends StatefulWidget {", + " @override", + " $1State createState() => $1State();", + "}", + "", + "class $1State extends State<$1> {", + " @override", + " Widget build(BuildContext context) {", + " return Scaffold(", + " appBar: AppBar(", + " title: Text('$2'),", + " ),", + " );", + " }", + " @override", + " void initState() {", + " // TODO: implement initState", + " super.initState();", + " }", + " ", + " @override", + " void dispose() {", + " // TODO: implement dispose", + " super.dispose();", + " }", + " ", + " @override", + " void didUpdateWidget($1 oldWidget) {", + " // TODO: implement didUpdateWidget", + " super.didUpdateWidget(oldWidget);", + " }", + " ", + " @override", + " void didChangeDependencies() {", + " // TODO: implement didChangeDependencies", + " super.didChangeDependencies();", + " }", + "}", + ], + "description": "创建完整的StatefulWidget,包含生命周期相关方法。" + }, + "创建StatelessWidget": { + "prefix": "stl", + "body": [ + "class $1 extends StatelessWidget {", + " @override", + " Widget build(BuildContext context) {", + " return Scaffold(", + " appBar: AppBar(", + " title: Text('$2'),", + " ),", + " );", + " }", + "}", + ], + "description": "创建StatelessWidget" + }, + + "创建CustomScrollView": { + "prefix": "svc", + "body": [ + "CustomScrollView(", + " slivers: [", + " //TODO", + " ],", + "),", + ], + "description": "创建CustomScrollView" + }, + + "创建一个标准的Text": { + "prefix": "te", + "body": [ + "Text('$1',", + " style: TextStyle(", + " color: Colors.$2, ", + " fontWeight: FontWeight.$3, ", + " fontSize: $4,", + " ),", + " textAlign: TextAlign.$5,", + " textDirection: TextDirection.$6,", + " textScaleFactor: $7,", + " overflow: TextOverflow.$8,", + " locale: Localizations.localeOf(context),", + " maxLines: $9,", + ");", + ], + "description": "创建一个标准的Text" + }, + +} \ No newline at end of file diff --git a/code_plugins/no_new_keywords/settings.jar b/code_plugins/no_new_keywords/settings.jar new file mode 100644 index 0000000..69cb546 Binary files /dev/null and b/code_plugins/no_new_keywords/settings.jar differ diff --git a/code_plugins/readme.md b/code_plugins/readme.md new file mode 100644 index 0000000..e5e83c3 --- /dev/null +++ b/code_plugins/readme.md @@ -0,0 +1,121 @@ +# README + +[English](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/code_plugins/readme.md)|[中文文档](https://github.com/AweiLoveAndroid/Flutter-learning/blob/master/code_plugins/README-CN.md) + +--- + +> Some Friends who use Flutter have a question, whether Android Studio or Intellij IDEA, they are not many of the shortcuts .Some friends are using the VSCode, maybe you can find the plugin to use, but it is not helpful for you. When you write some codes that you use every day, you can't use the shortcut to generate the code you want. So I wrote the common Flutter code live templates, and then you can use it in Android Studio, Intellij IDEA and VSCode. + +### 1.Precautions + +* 1.Do not make any changes to the settings.jar file, otherwise please re-download the settings.jar flie. +* 2.After importing, if the shortcut is not working, please check whether the code completions are correct in Android Studio or Intellij IDEA. + +--- + +### 2.Set the fuzzy match: + +> old version +Click menu bar `File → Settings → Editor → General → Code Completion → Case Sensitive Complete → NONE` + +![](https://upload-images.jianshu.io/upload_images/6098829-183dce2a0499b0d6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/702/format/webp) + +> new version + +Click menu bar `File → Settings → Editor → General → Code Completion → Delete the check button in front of the Match cases` + +![](https://upload-images.jianshu.io/upload_images/6098829-3194305ecb760fbe.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/556/format/webp) + +--- + +### 3.How to import a project? + +> Import into Android Studio or Intellij IDEA + +First open github [https://github.com/AweiLoveAndroid/Flutter-learning/tree/master/code_plugins](https://github.com/AweiLoveAndroid/Flutter-learning/tree/master/code_plugins) and download the `settings.jar` file. The jar flie can be placed in any English file path. +Then, click the menu bar `File → Import Settings`, then find the `settings.jar` that you had downloaded and import it. + +![](https://upload-images.jianshu.io/upload_images/6098829-450d5f8e17341ba7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/270/format/webp) + +Then select the `live template` and `live template (schemes)` and click the `OK` button. + +![](https://upload-images.jianshu.io/upload_images/6098829-5a16c2468a36d9d8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/541/format/webp) + +* **Tips: If you don't want to use the keywords `new`, you should download the [no_new_keywords/settings.jar](https://github.com/AweiLoveAndroid/Flutter-learning/tree/master/code_plugins/no_new_keywords/settings.jar) file, otherwise you should download the [have_new_keywords/settings.jar](https://github.com/AweiLoveAndroid/Flutter-learning/tree/master/code_plugins/have_new_keywords/settings.jar) file.** + +> Import into VSCode + +For VSCode users, download the `dart.json` file and copy it to `C:\ Users\ Administrator \ AppData \ Roaming \ Code \ User \ Snippets \ directory (user is the username in the computer)`. If the file `dart.json` already exists, please replace it. + +* **Tips: If you don't want to use the keywords `new`, you should download the [no_new_keywords/dart.json](https://github.com/AweiLoveAndroid/Flutter-learning/tree/master/code_plugins/no_new_keywords/dart.json) file, otherwise you should download the [have_new_keywords/dart.json](https://github.com/AweiLoveAndroid/Flutter-learning/tree/master/code_plugins/have_new_keywords/dart.json) file.** + +--- + +4.Supported shortcuts + +Short keys|Description +----|---- +bab| Create AnimatedBuilder +bu| Create Build() +bufb| Create FutureBuilder +bulb| Create LayoutBuilder +buob| Create OrientationBuilder +bustf| Create StatefulBuilder +bustr| Create StreamBuilder +cc| Create CustomClipper +cen| Create Center +col| Create Column +con| Create full Container +cp| Create your CustomPainter +csv| CustomScrollView + SliverPadding and its child with padding. +csv2| use CustomScrollView + SliverGrid +gv| Create GridView.count +inh| Create Inherited +lv| Create normal ListView +lvb| Create ListView.builder +lvd |Create ListView with divider +lvr| Create RadioListTile +lvt| Create ListView with more ListTile +mainstf |Create StatefulWidget +mainstl| Create StatelessWidget +me |Create methods +mep| Create private methods +row| Create Row +sb |Create SizedBox +ssv| Create SingleChildScrollView +stanim| Create Stateful(with AnimationController) +stf |Create full StatefulWidget with full lifecycle +stl |Create StatelessWidget +svc |Create CustomScrollView +te| Create normal Text + +--- + +5.Some shortcuts usage + +mainstf: + +![](https://upload-images.jianshu.io/upload_images/6098829-a715d299b3c4d2b6.gif?imageMogr2/auto-orient/strip%7CimageView2/2/w/418/format/webp) + +mainstl: + +![](https://upload-images.jianshu.io/upload_images/6098829-2042bdf5fb3a157a.gif?imageMogr2/auto-orient/strip%7CimageView2/2/w/418/format/webp) + +stf: + +![](https://upload-images.jianshu.io/upload_images/6098829-7e796ef45a0d5cd6.gif?imageMogr2/auto-orient/strip%7CimageView2/2/w/418/format/webp) + +stl: + +![](https://upload-images.jianshu.io/upload_images/6098829-b1549c03b9a9b5ee.gif?imageMogr2/auto-orient/strip%7CimageView2/2/w/418/format/webp) + +gv: + +![](https://upload-images.jianshu.io/upload_images/6098829-6c5985388f267fdc.gif?imageMogr2/auto-orient/strip%7CimageView2/2/w/647/format/webp) + +lv: + +![](https://upload-images.jianshu.io/upload_images/6098829-04f30b3523027724.gif?imageMogr2/auto-orient/strip%7CimageView2/2/w/418/format/webp) + +con: +![](https://upload-images.jianshu.io/upload_images/6098829-374bb9d45ba2e3ea.gif?imageMogr2/auto-orient/strip%7CimageView2/2/w/647/format/webp) diff --git a/code_plugins/settings.jar b/code_plugins/settings.jar deleted file mode 100644 index a6150ee..0000000 Binary files a/code_plugins/settings.jar and /dev/null differ diff --git "a/flutter-learning-doc-resources/Flutter\346\234\211\345\205\263\345\215\232\345\256\242\350\256\262\350\247\243.md" "b/flutter-learning-doc-resources/Flutter\346\234\211\345\205\263\345\215\232\345\256\242\350\256\262\350\247\243.md" index 1e60418..50cde2e 100644 --- "a/flutter-learning-doc-resources/Flutter\346\234\211\345\205\263\345\215\232\345\256\242\350\256\262\350\247\243.md" +++ "b/flutter-learning-doc-resources/Flutter\346\234\211\345\205\263\345\215\232\345\256\242\350\256\262\350\247\243.md" @@ -1,13 +1,29 @@ -Android Flutter实践内存初探--闲鱼团队编写的博客 https://zhuanlan.zhihu.com/p/36488644 +# 我写的Flutter干货博客: -移动开发新利器 一文深入了解 Flutter 界面开发 https://yq.aliyun.com/articles/599868 +#### [安卓开发方式的进化之路]( https://www.jianshu.com/p/44305a99c51a) -Dart语言指南(一) https://my.oschina.net/u/3647851/blog/1594311 +#### [跨平台开发框架和工具集锦](https://www.jianshu.com/p/de459708d9ed) -Dart语言指南(二) https://my.oschina.net/u/3647851/blog/1792031 +#### [Flutter从配置安装到填坑指南详解](https://www.jianshu.com/p/399c01657920) +#### [老司机用一篇博客带你快速熟悉Dart语法](https://www.jianshu.com/p/3d927a7bf020) +#### [Flutter学习总结系列----第一章、Flutter基础全面详解](https://www.jianshu.com/p/2c9867e737a1) -项目教学网址: https://marcinszalek.pl/flutter/filter-menu-ui-challenge/ +#### [Flutter代码模板,解放双手,提高开发效率必备](https://www.jianshu.com/p/4184745d6983) -群友写的项目源码: https://github.com/bergejun/flutter_study +#### [Flutter布局篇(1)--水平和垂直布局详解](https://www.jianshu.com/p/7511cb18a05e) + +#### [Flutter填坑全面总结](https://www.jianshu.com/p/22675c1632dc) + +#### [Flutter 的手势(GestureDetector)分析详解](https://www.jianshu.com/p/3b87ddb022af) + +#### [Flutter路由详解](https://www.jianshu.com/p/6e399b45bbb7) + +#### [手把手带你快速上手调试Flutter项目](https://www.jianshu.com/p/97c4df211791) + +---- + +#### 简书博客:https://www.jianshu.com/u/f408bdadacce +#### 掘金博客:https://juejin.im/user/5a07c6c0f265da430a501017 +#### 安卓巴士博客:http://www.apkbus.com/space-uid-944603.html \ No newline at end of file diff --git a/learn-plan.md b/learn-plan.md deleted file mode 100644 index 62e5c25..0000000 --- a/learn-plan.md +++ /dev/null @@ -1,13 +0,0 @@ -# 学习计划 - -##### 一、UI开发:基本布局、样式、主题、国际化、程序调试 - -##### 二、页面跳转、路由、数据传递 - -##### 三、数据存储:xml json处理 - -##### 四、数据库: - -##### 五、网络编程: - -##### 五、高级编程:图片处理、动画交互、播放音视频、和Android原生api的交互、自定义控件 diff --git "a/pics/Dart\347\232\204\346\250\241\346\235\277\350\256\276\347\275\256.png" "b/pics/Dart\347\232\204\346\250\241\346\235\277\350\256\276\347\275\256.png" new file mode 100644 index 0000000..bd5f8b0 Binary files /dev/null and "b/pics/Dart\347\232\204\346\250\241\346\235\277\350\256\276\347\275\256.png" differ diff --git "a/pics/Dart\347\274\226\350\276\221\346\250\241\346\235\277\345\255\227\346\256\265.png" "b/pics/Dart\347\274\226\350\276\221\346\250\241\346\235\277\345\255\227\346\256\265.png" new file mode 100644 index 0000000..15ea387 Binary files /dev/null and "b/pics/Dart\347\274\226\350\276\221\346\250\241\346\235\277\345\255\227\346\256\265.png" differ diff --git a/pics/donation.png b/pics/donation.png index a255c91..7a4ec95 100644 Binary files a/pics/donation.png and b/pics/donation.png differ diff --git a/pics/logo.png b/pics/logo.png new file mode 100644 index 0000000..5f5ce95 Binary files /dev/null and b/pics/logo.png differ diff --git "a/pics/\345\205\254\344\274\227\345\217\267\344\272\214\347\273\264\347\240\201.jpg" "b/pics/\345\205\254\344\274\227\345\217\267\344\272\214\347\273\264\347\240\201.jpg" new file mode 100644 index 0000000..d35a112 Binary files /dev/null and "b/pics/\345\205\254\344\274\227\345\217\267\344\272\214\347\273\264\347\240\201.jpg" differ diff --git a/projects/dart_demo/README.md b/projects/dart_demo/README.md index 72948b4..8eca332 100644 --- a/projects/dart_demo/README.md +++ b/projects/dart_demo/README.md @@ -1,8 +1,12 @@ # dart_demo -A new Flutter application. - -## Getting Started - -For help getting started with Flutter, view our online -[documentation](https://flutter.io/). +#### [变量和常量](test/3-variable_and_constant) +#### [特殊数据类型](test/4-datas-type) +#### [运算符](test/5-opertors) +#### [控制流程语句](test/6-control_flow_statements) +#### [异常](test/7-exception) +#### [类与函数](test/8-class) +#### [库和可见性](test/9-library) +#### [异步支持](test/10-async_demo) +#### [生成器(Generators)](test/11-generator) +#### [Isolates](test/12-isolate) \ No newline at end of file diff --git a/projects/dart_demo/lib/ConvertNumberToChineseMoneyWords.dart b/projects/dart_demo/lib/ConvertNumberToChineseMoneyWords.dart new file mode 100644 index 0000000..ae198b7 --- /dev/null +++ b/projects/dart_demo/lib/ConvertNumberToChineseMoneyWords.dart @@ -0,0 +1,178 @@ +// 测试一下 把数字转成中文金额大写 +void main() { + // 输出结果: + // 转换前数字: 45.12 + // 转换后的中文大写: 肆拾伍元壹角贰分 + // + // 转换前数字: 97953164651665.123 + // 转换后的中文大写: 玖拾柒万玖仟伍佰叁拾壹亿陆仟肆佰陆拾伍万壹仟陆佰陆拾伍元壹角贰分叁厘 + // + // 转换前数字: 25000 + // 转换后的中文大写: 贰万伍仟元 + // + // 转换前数字: 363,5 + // 转换后的中文大写: 叁仟陆佰叁拾伍元 + + String number = "45.12"; + ConvertNumberToChineseMoneyWords numbers = + new ConvertNumberToChineseMoneyWords(); + print("转换前数字: " + number + " ,转换后的中文大写: " + numbers.toChinese(number) + "\n"); + number = "97953164651665.123"; + print("转换前数字: " + number + " ,转换后的中文大写: " + numbers.toChinese(number) + "\n"); + number = "25000"; + print("转换前数字: " + number + " ,转换后的中文大写: " + numbers.toChinese(number) + "\n"); + number = "363,5"; + print("转换前数字: " + number + " ,转换后的中文大写: " + numbers.toChinese(number) + "\n"); +} + + +////////////////////////////////////////////////////////////////////////////////// +///////// +///////// 以下才是工具类的完整内容 +//////// +////////////////////////////////////////////////////////////////////////////////// + + +/* + * 把数字转换成中文金额大写工具类 + */ +class ConvertNumberToChineseMoneyWords { + // 大写数字 + List NUMBERS = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"]; + + // 整数部分的单位 + List IUNIT = [ + "元", + "拾", + "佰", + "仟", + "万", + "拾", + "佰", + "仟", + "亿", + "拾", + "佰", + "仟", + "万", + "拾", + "佰", + "仟" + ]; + + // 小数部分的单位 + List DUNIT = ["角", "分", "厘"]; + + //转成中文的大写金额 + String toChinese(String str) { + if (str == "0" || str == "0.00") { + return "零元"; + } + // 去掉"," + str = str.replaceAll(",", ""); + // 整数部分数字 + String integerStr; + // 小数部分数字 + String decimalStr; + + // 初始化:分离整数部分和小数部分 + if (str.indexOf(".") > 0) { + integerStr = str.substring(0, str.indexOf(".")); + decimalStr = str.substring(str.indexOf(".") + 1); + } else if (str.indexOf(".") == 0) { + integerStr = ""; + decimalStr = str.substring(1); + } else { + integerStr = str; + decimalStr = ""; + } + + // 超出计算能力,直接返回 + if (integerStr.length > IUNIT.length) { + print(str + ":超出计算能力"); + return str; + } + + // 整数部分数字 + var integers = toIntArray(integerStr); + // 设置万单位 + bool isWan = isWanYuan(integerStr); + // 小数部分数字 + var decimals = toIntArray(decimalStr); + // 返回最终的大写金额 + return getChineseInteger(integers, isWan) + getChineseDecimal(decimals); + } + + // 将字符串转为int数组 + static List toIntArray(String number) { + List array = []; + if (array.length > number.length) { + throw new Exception("数组越界异常"); + } else { + for (int i = 0; i < number.length; i++) { + array.insert(i, int.parse(number.substring(i, i + 1))); + } + return array; + } + } + + // 判断当前整数部分是否已经是达到【万】 + static bool isWanYuan(String integerStr) { + int length = integerStr.length; + if (length > 4) { + String subInteger = ""; + if (length > 8) { + subInteger = integerStr.substring(length - 8, length - 4); + } else { + subInteger = integerStr.substring(0, length - 4); + } + return int.parse(subInteger) > 0; + } else { + return false; + } + } + + // 将整数部分转为大写的金额 + String getChineseInteger(var integers, bool isWan) { + StringBuffer chineseInteger = new StringBuffer(""); + int length = integers.length; + for (int i = 0; i < length; i++) { + String key = ""; + if (integers[i] == 0) { + // 万(亿) + if ((length - i) == 13) + key = IUNIT[4]; + else if ((length - i) == 9) { + // 亿 + key = IUNIT[8]; + } else if ((length - i) == 5 && isWan) { + // 万 + key = IUNIT[4]; + } else if ((length - i) == 1) { + // 元 + key = IUNIT[0]; + } + if ((length - i) > 1 && integers[i + 1] != 0) { + key += NUMBERS[0]; + } + } + chineseInteger.write(integers[i] == 0 + ? key + : (NUMBERS[integers[i]] + IUNIT[length - i - 1])); + } + return chineseInteger.toString(); + } + + // 将小数部分转为大写的金额 + String getChineseDecimal(var decimals) { + StringBuffer chineseDecimal = new StringBuffer(""); + for (int i = 0; i < decimals.length; i++) { + if (i == 3) { + break; + } + chineseDecimal + .write(decimals[i] == 0 ? "" : (NUMBERS[decimals[i]] + DUNIT[i])); + } + return chineseDecimal.toString(); + } +} diff --git a/projects/dart_demo/test/10-async_demo/11-2-async&await/async_demo0.dart b/projects/dart_demo/test/10-async_demo/11-2-async&await/async_demo0.dart new file mode 100644 index 0000000..f8099cf --- /dev/null +++ b/projects/dart_demo/test/10-async_demo/11-2-async&await/async_demo0.dart @@ -0,0 +1,14 @@ +import 'dart:async'; + +// async延迟功能 +main() { + foo(499).then(print); + print("after foo call"); +} + + +Future foo(x) async { + print(x); + return x + 1; +} + diff --git a/projects/dart_demo/test/10-async_demo/11-2-async&await/async_demo01.dart b/projects/dart_demo/test/10-async_demo/11-2-async&await/async_demo01.dart new file mode 100644 index 0000000..c342e58 --- /dev/null +++ b/projects/dart_demo/test/10-async_demo/11-2-async&await/async_demo01.dart @@ -0,0 +1,14 @@ +import 'dart:async'; + +void main(){ + checkVersion(); +} + +Future checkVersion() async { + var version = await lookUpVersion(); + // 其他操作 +} + +void lookUpVersion(){ + // 逻辑... +} \ No newline at end of file diff --git a/projects/dart_demo/test/10-async_demo/11-2-async&await/async_demo02.dart b/projects/dart_demo/test/10-async_demo/11-2-async&await/async_demo02.dart new file mode 100644 index 0000000..2970b3f --- /dev/null +++ b/projects/dart_demo/test/10-async_demo/11-2-async&await/async_demo02.dart @@ -0,0 +1,19 @@ +import 'dart:async'; + +void main() { + checkVersion(); +} + +Future checkVersion() async { + try { + var version = await lookUpVersion(); + } catch (e) { + // 这里可以看到是什么错误。 + } finally { + // 正确的解决方式写在这里 + } +} + +void lookUpVersion() { + // 逻辑... +} diff --git a/projects/dart_demo/test/10-async_demo/11-2-async&await/async_demo03.dart b/projects/dart_demo/test/10-async_demo/11-2-async&await/async_demo03.dart new file mode 100644 index 0000000..4244093 --- /dev/null +++ b/projects/dart_demo/test/10-async_demo/11-2-async&await/async_demo03.dart @@ -0,0 +1,26 @@ +import 'dart:async'; + +void main() { + checkVersion(); +} + +Future checkVersion() async { + var entrypoint = await findEntrypoint(); + var exitCode = await runExecutable(entrypoint, 10); + await flushThenExit(exitCode); +} + +String findEntrypoint() { + // 逻辑... + return 'entrypoint'; +} + +String runExecutable(String entrypoint, int args) { + // 逻辑... + return 'executable'; +} + +String flushThenExit(String executable) { + // 逻辑... + return 'exit'; +} \ No newline at end of file diff --git a/projects/dart_demo/test/10-async_demo/11-2-async&await/async_demo04.dart b/projects/dart_demo/test/10-async_demo/11-2-async&await/async_demo04.dart new file mode 100644 index 0000000..95ab132 --- /dev/null +++ b/projects/dart_demo/test/10-async_demo/11-2-async&await/async_demo04.dart @@ -0,0 +1,23 @@ +import 'dart:async'; + +// 要在应用程序的main()函数中使用await,main()方法必须标记为async + +// 结果: +// checkVersion() +// lookUpVersion() +// lookUpVersion() +// In main: version is 版本号:v1.0 +Future main() async { + checkVersion(); + print('In main: version is ${await lookUpVersion()}'); +} + +Future checkVersion() async { + print('checkVersion()'); + var version = await lookUpVersion(); +} + +Future lookUpVersion() async{ + print('lookUpVersion()'); + return '版本号:v1.0'; +} \ No newline at end of file diff --git a/projects/dart_demo/test/10-async_demo/11-3-define_asynchronous_function/define_demo.dart b/projects/dart_demo/test/10-async_demo/11-3-define_asynchronous_function/define_demo.dart new file mode 100644 index 0000000..9b67475 --- /dev/null +++ b/projects/dart_demo/test/10-async_demo/11-3-define_asynchronous_function/define_demo.dart @@ -0,0 +1,24 @@ +import 'dart:async'; + +void main(){ + lookUpVersion(); // 输出结果:lookUpVersion()同步方法 返回值是:1.0.0 + lookUpVersion2(); // 输出结果:lookUpVersion2()异步方法 返回值是:1.0.0 + lookUpVersion3(); // 输出结果:lookUpVersion3()异步方法 没有返回值 +} + + +String lookUpVersion() { + print('lookUpVersion()同步方法 返回值是:1.0.0'); + return '1.0.0'; +} + +// 返回值Future +Future lookUpVersion2() async { + print('lookUpVersion2()异步方法 返回值是:1.0.0'); + return '1.0.0'; +} + +// 返回值Future +Future lookUpVersion3() async { + print('lookUpVersion3()异步方法 没有返回值'); +} \ No newline at end of file diff --git a/projects/dart_demo/test/10-async_demo/11-4-stream/stream_demo.dart b/projects/dart_demo/test/10-async_demo/11-4-stream/stream_demo.dart new file mode 100644 index 0000000..63bab98 --- /dev/null +++ b/projects/dart_demo/test/10-async_demo/11-4-stream/stream_demo.dart @@ -0,0 +1,27 @@ +import 'dart:io'; +import 'dart:convert'; + +void main() { + test(); +} + +// await for循环的使用示例 +// 这里是读取本地文件的内容 +Future test() async { + var config = File('d:\\test.txt'); + // 打开io流进行文件读取 + Stream> inputStream = config.openRead(); + var lines = inputStream + // 设置编码格式为utf-8 + .transform(utf8.decoder) + .transform(LineSplitter()); + try { + await for (var line in lines) { + print('从Stream中获取到的内容是: ${line} \r文本内容长度为:'+ + '${line.length}\r======='); + } + print('文件现在没有关闭。。。'); + } catch (e) { + print(e); + } +} \ No newline at end of file diff --git a/projects/dart_demo/test/10-async_demo/test.txt b/projects/dart_demo/test/10-async_demo/test.txt new file mode 100644 index 0000000..2643d31 --- /dev/null +++ b/projects/dart_demo/test/10-async_demo/test.txt @@ -0,0 +1,5 @@ +这是测试内容: +123456 +文字 +abcdefg +ABCDEFG \ No newline at end of file diff --git a/projects/dart_demo/test/11-generator/generate_demo.dart b/projects/dart_demo/test/11-generator/generate_demo.dart new file mode 100644 index 0000000..0b74031 --- /dev/null +++ b/projects/dart_demo/test/11-generator/generate_demo.dart @@ -0,0 +1,21 @@ +void main() { + // 返回一个Iterable对象 + Iterable naturalsTo(int n) sync* { + int k = 0; + while (k < n) yield k++; + } + + // 生成器是递归的,您可以使用yield*提高性能 + Iterable naturalsDownFrom(int n) sync* { + if (n > 0) { + yield n; + yield* naturalsDownFrom(n - 1); + } + } + + // 返回一个Stream对象 + Stream asynchronousNaturalsTo(int n) async* { + int k = 0; + while (k < n) yield k++; + } +} diff --git a/projects/dart_demo/test/12-isolate/isolates_demo.dart b/projects/dart_demo/test/12-isolate/isolates_demo.dart new file mode 100644 index 0000000..0c5fe08 --- /dev/null +++ b/projects/dart_demo/test/12-isolate/isolates_demo.dart @@ -0,0 +1,41 @@ +import 'dart:isolate'; +import 'dart:io'; +import 'dart:convert'; + +// 在另一个隔离区()中同步读取“D://file.json” +// 结果是{msg: [{title: 你好1, contents: yes}, {title: 你好2, contents: NO}]} +main() async { + // 在其他隔离(isolate)中同步读取文件,然后对其进行解码。 + print(await readIsolate()); +} + +// 同步读取'D//file.json'(在同一个线程中) +Map readSync() { +JsonCodec().decode(new File('D://file.json').readAsStringSync()); +} + +// 在另一个隔离区()中同步读取“D://file.json” +Future readIsolate() async { + final response = new ReceivePort(); + await Isolate.spawn(_isolate, response.sendPort); + return response.first; +} + +/// 期望通过[Isolate.spawn]创建 +void _isolate(SendPort sendPort) { + sendPort.send(readSync()); +} + +// 下面是file.json文件的内容: +// { +// "msg": [ +// { +// "title": "你好1", +// "contents": "yes" +// }, +// { +// "title": "你好2", +// "contents": "NO" +// } +// ] +// } diff --git a/projects/dart_demo/test/3-variable_and_constant/3-1-variable_and_constant1.dart b/projects/dart_demo/test/3-variable_and_constant/3-1-variable_and_constant1.dart new file mode 100644 index 0000000..24ecc7f --- /dev/null +++ b/projects/dart_demo/test/3-variable_and_constant/3-1-variable_and_constant1.dart @@ -0,0 +1,6 @@ +void main() { + // 1.变量的声明3种方式: + var names1 = '张三'; + Object names2 = '张三'; + dynamic name3 = '李四'; +} diff --git a/projects/dart_demo/test/3-variable_and_constant/3-2-variable_and_constant2.dart b/projects/dart_demo/test/3-variable_and_constant/3-2-variable_and_constant2.dart new file mode 100644 index 0000000..6d2c0ee --- /dev/null +++ b/projects/dart_demo/test/3-variable_and_constant/3-2-variable_and_constant2.dart @@ -0,0 +1,6 @@ +void main() { + // 2.变量的默认值: + int intDefaultValue; + assert(intDefaultValue == null); + print(intDefaultValue); // null +} diff --git a/projects/dart_demo/test/3-variable_and_constant/3-3-variable_and_constant3.dart b/projects/dart_demo/test/3-variable_and_constant/3-3-variable_and_constant3.dart new file mode 100644 index 0000000..4cdf665 --- /dev/null +++ b/projects/dart_demo/test/3-variable_and_constant/3-3-variable_and_constant3.dart @@ -0,0 +1,87 @@ +// 3. final 和 const 示例 +void main() { + test1(); + test2(); + test3(); + test4(); + test5(); + test6(); +} + +void test1() { + //可以省略类型声明 + final name1 = "张三"; + //final String name1 = "张三"; + const name2 = "李四"; + //const String name2 = "李四" +} + +void test2() { + //这样写都会报错 + //final var name1 = "张三"; + //const var name2 = "李四"; +} + +void test3() { + final name1 = "张三"; + // 如果这样写,编译器提示:a final variable, can only be set once + // 一个final变量,只能被设置一次。 + //name1 = "zhangsan"; + + const name2 = "李四"; + // 这样写,编译器提示:Constant variables can't be assigned a value + // const常量不能赋值 + // name2 = "lisi"; +} + +// 运算 +void test4() { + const units = 60; //(单位: s/min) + const seconds1 = units * 20; //秒数=60*分钟数 结果为:1200 + + const minutes = 20; //20分钟 + const seconds2 = units * minutes; //秒数=60*分钟数 结果为:1200 + + final speed1 = 100; //速度(km/h) + final double distance1 = speed1 * 2.5; // 距离 = 速度*时间,结果为:250.0 + + double time = 2.5; + final double distance2 = speed1 * time; // 距离 = 速度*时间,结果为:250.0 +} + +// const更多用法 +void test5() { + // const[]创建一个空的、不可变的列表(EIL) + var varList = const []; // varList 当前是一个EIL + final finalList = const []; // finalList一直是EIL + const constList = const []; // constList 是一个编译时常量的EIL + + varList = ["haha"]; + + // 不能更改final变量或const变量的值 + // 这样写,编译器提示:a final variable, can only be set once + // finalList = ["haha"]; + + // 这样写,编译器提示:Constant variables can't be assigned a value + // constList = ["haha"]; +} + +// 常量字符串 +void test6() { + // 这些是常量字符串 + const aConstNum = 0; + const aConstBool = true; + const aConstString = '常量字符串'; + + const validConstString = '$aConstNum $aConstBool $aConstString null'; + + // 这些不是常量字符串 + var aNum = 0; + var aBool = true; + var aString = '这是String字符串'; + const aConstList = const [1, 2, 3]; + + // const常量必须用const类型的值初始化。 + //这样用就会报错:Const variables must be initialized with a constant value + // const invalidConstString = '$aNum $aBool $aString $aConstList'; +} diff --git a/projects/dart_demo/test/4-datas-type/4-1-num_demo.dart b/projects/dart_demo/test/4-datas-type/4-1-num_demo.dart new file mode 100644 index 0000000..2e7f905 --- /dev/null +++ b/projects/dart_demo/test/4-datas-type/4-1-num_demo.dart @@ -0,0 +1,44 @@ +void main() { + test1(); + test2(); +} + +// int 示例 +void test1() { + int intNum1 = 10; + print(intNum1); //结果是10 + int intNum2 = 0xDEADBEEF; + print(intNum2); //结果是3735928559 + + // bitLength 返回存储此int整数所需的最小位数 + int a1 = 1; // 占了1个bit 相当于二进制数字 00000000 00000001 + int a2 = 12; // 占了4个bit 相当于二进制数字 00000000 00001100 + int a3 = 123; // 占了7个bit 相当于二进制数字 00000000 01111011 + int a4 = 1234; // 占了11个bit 相当于二进制数字 00000100 11010010 + print('${a1.bitLength}'); // 1 + print('${a2.bitLength}'); // 4 + print('${a3.bitLength}'); // 7 + print('${a4.bitLength}'); // 11 +} + +// double示例 +void test2() { + double doubleNum1 = 1.1; + print(doubleNum1); //结果是1.1 + double doubleNum2 = 1.42e5; + print(doubleNum2); //结果是142000.0 + + // int自动转double + double test = 12; //打印结果是12.0 + print(test); //打印结果是12.0 + + // 使用int的api转double + int test2 = 10; + print(test2.toDouble()); // 结果是: 10.0 + + // double转int + double test3 = 15.1; + double test4 = 15.1234; + print(test3.toInt()); // 结果是15 + print(test4.toInt()); // 结果是15 +} diff --git a/projects/dart_demo/test/4-datas-type/4-2-String_demo.dart b/projects/dart_demo/test/4-datas-type/4-2-String_demo.dart new file mode 100644 index 0000000..51816a7 --- /dev/null +++ b/projects/dart_demo/test/4-datas-type/4-2-String_demo.dart @@ -0,0 +1,93 @@ +// String示例 +void main() { + test1(); + test2(); + test3(); + test4(); + test5(); + test6(); +} + +void test1() { + String str1 = '单引号基本使用demo.'; + String str2 = "双引号基本使用demo."; +} + +void test2() { + //单引号里面嵌套单引号,必须在前面加反斜杠 + String str3 = '双引号里面有单引号it\'s,必须在前面加反斜杠.'; + //双引号里面嵌套单引号(正常使用) + String str4 = "双引号里面有单引号it's."; + //单引号里面嵌套双引号(正常使用) + String str5 = '单引号里面有双引号,"hello world"'; + //双引号里面嵌套双引号,必须在前面加反斜杠 + String str6 = "双引号里面有双引号,\"hello world\""; + + print(str3); // 双引号里面有单引号it's,必须在前面加反斜杠. + print(str4); // 双引号里面有单引号it's. + print(str5); // 单引号里面有双引号,hello world" + print(str6); //双引号里面有双引号,"hello world" +} + +void test3() { + // 这个会报错 + //String blankStr1 = 'hello''''world'; + // 这两个运行正常 + String blankStr2 = 'hello' ' ' 'world'; //结果: hello world + String blankStr3 = 'hello' '_' 'world'; //结果: hello_world + + // 这个会报错 + //String blankStr4 = "hello""""world"; + // 这两个运行正常 + String blankStr5 = "hello" " " "world"; //结果: hello world + String blankStr6 = "hello" "_" "world"; //结果: hello_world + + //单引号里面有双引号,混合使用运行正常 + String blankStr7 = 'hello""""world'; //结果: hello""""world + String blankStr8 = 'hello"" ""world'; //结果: hello"" ""world + String blankStr9 = 'hello""_""world'; //结果: hello""_""world + + //双引号里面有单引号,混合使用运行正常 + String blankStr10 = "hello''''world"; //结果: hello''''world + String blankStr11 = "hello'' ''world"; //结果: hello'' ''world + String blankStr12 = "hello''_''world"; //结果: hello''_''world +} + +// 字符串拼接 +void test4() { + String connectionStr1 = '字符串连接' '甚至可以在' '换行的时候进行。'; + print(connectionStr1); // 字符串连接甚至可以在换行的时候进行。 + + String connectionStr2 = '字符串连接' + '甚至可以在' + '换行的时候进行。'; + print(connectionStr2); // 字符串连接甚至可以在换行的时候进行。 + + String connectionStr3 = ''' + 这是用单引号创建的 + 多行字符串。 + '''; + print(connectionStr3); + + String connectionStr4 = """这是用双引号创建的 + 多行字符串。"""; + print(connectionStr4); +} + +// 转义字符 +void test5() { + print(r"换行符:\n"); //这个结果是 换行符:\n + print("换行符:\\n"); //这个结果是 换行符:\n + print("换行符:\n"); //这个结果是 换行符 +} + +void test6() { + var height = 48.0; + print('当前标题的高度是$height'); //当前标题的高度是48.0 + + String name = "张三"; + print("$name" + "是我们的部门经理"); // 张三是我们的部门经理 + + String replaceStr = 'Android Studio'; + assert('你知道' + '${replaceStr.toUpperCase()}' + + '最新版本是多少吗?' == + '你知道ANDROID STUDIO最新版本是多少吗?'); +} diff --git a/projects/dart_demo/test/4-datas-type/4-3-bool_demo.dart b/projects/dart_demo/test/4-datas-type/4-3-bool_demo.dart new file mode 100644 index 0000000..d159209 --- /dev/null +++ b/projects/dart_demo/test/4-datas-type/4-3-bool_demo.dart @@ -0,0 +1,23 @@ +// bool示例 +void main() { + test(); +} + +void test() { + + // 检查是否为空字符串 + var emptyStr = ''; + assert(emptyStr.isEmpty); + + // 检查是否为0 + var numberStr = 0; + assert(numberStr <= 0); + + // 检查是否为null + var nullStr; + assert(nullStr == null); + + // 检查是否为NaN + var value = 0 / 0; + assert(value.isNaN); +} diff --git a/projects/dart_demo/test/4-datas-type/4-4-list_demo.dart b/projects/dart_demo/test/4-datas-type/4-4-list_demo.dart new file mode 100644 index 0000000..1ac00f3 --- /dev/null +++ b/projects/dart_demo/test/4-datas-type/4-4-list_demo.dart @@ -0,0 +1,38 @@ +void main() { + test(); + test2(); +} + +void test() { + //创建一个int类型的list + List list = [10, 7, 23]; + print(list); // 输出结果 [10, 7, 23] + + // 要创建一个编译时常量const的list + List constantList = const [10, 3, 15]; + print(constantList); // 输出结果 [10, 3, 15] +} + +void test2() { + //把数字1添加到list中,默认是添加到末尾 + List list = [10, 7, 23]; + list.add(1); + print(list); // 输出结果 [10, 7, 23, 1] + + //移除数字1 + list.remove(1); + print(list); // 输出结果 [10, 7, 23] + + //在索引为0的地方插入数字5 + list.insert(0, 5); + print(list); // 输出结果 [5, 10, 7, 23] + + //查找10在list中的索引 + int value = list.indexOf(10); + print(value); // 输出结果 1 + + //查找list中是否包含数字5 + bool result = list.contains(5); + print(result);// 输出结果 true + +} diff --git a/projects/dart_demo/test/4-datas-type/4-5-map_demo.dart b/projects/dart_demo/test/4-datas-type/4-5-map_demo.dart new file mode 100644 index 0000000..0d682af --- /dev/null +++ b/projects/dart_demo/test/4-datas-type/4-5-map_demo.dart @@ -0,0 +1,46 @@ +void main() { + test1(); + test2(); +} + +// 创建 +void test1() { + // 直接声明 + Map companys = {'first': '阿里巴巴', 'second': '腾讯', 'fifth': '百度'}; + print(companys); //打印结果 {first: 阿里巴巴, second: 腾讯, fifth: 百度} + + Map companys1 = new Map(); + companys1['first'] = '阿里巴巴'; + companys1['second'] = '腾讯'; + companys1['fifth'] = '百度'; + print(companys1); //打印结果 {first: 阿里巴巴, second: 腾讯, fifth: 百度} + + final fruitConstantMap = const {2: 'apple', 10: 'orange', 18: 'banana'}; + print(fruitConstantMap); // {2: apple, 10: orange, 18: banana} +} + +// 增删改查 +void test2() { + Map companys = {'first': '阿里巴巴', 'second': '腾讯', 'fifth': '百度'}; + + //添加一个新的元素,key为“5”,value为“华为” + companys[5] = '华为'; + print(companys); //打印结果 {first: 阿里巴巴, second: 腾讯, fifth: 百度, 5: 华为} + + // 修改元素 + companys['first'] = 'alibaba'; + print(companys); //打印结果 {first: alibaba, second: 腾讯, fifth: 百度, 5: 华为} + + // 查询元素 + bool mapKey = companys.containsKey('second'); + bool mapValue = companys.containsValue('百度'); + print(mapKey); //结果为:true + print(mapValue); //结果为:true + + // 删除元素 + companys.remove('first'); // 移除key为“first”的元素。 + print(companys); // 打印结果{second: 腾讯, fifth: 百度, 5: 华为} + + companys.clear(); // 清空map集合的数据。 + print(companys); // 打印结果{} +} diff --git a/projects/dart_demo/test/4-datas-type/4-6-runes_demo.dart b/projects/dart_demo/test/4-datas-type/4-6-runes_demo.dart new file mode 100644 index 0000000..f72507f --- /dev/null +++ b/projects/dart_demo/test/4-datas-type/4-6-runes_demo.dart @@ -0,0 +1,16 @@ +// runes 字符(用于在字符串中表示Unicode字符) +void main() { + test(); +} + +void test() { + var clapping = '\u{1f44f}'; + print(clapping); + print(clapping.codeUnits); + print(clapping.runes.toList()); + + //这里使用String.fromCharCodes方法显示字符图形 + Runes input = new Runes( + '\u2665 \u{1f605} \u{1f60e} \u{1f47b} \u{1f596} \u{1f44d}'); + print(new String.fromCharCodes(input)); +} diff --git a/projects/dart_demo/test/5-opertors/opertors_demo.dart b/projects/dart_demo/test/5-opertors/opertors_demo.dart new file mode 100644 index 0000000..086c9fc --- /dev/null +++ b/projects/dart_demo/test/5-opertors/opertors_demo.dart @@ -0,0 +1,146 @@ +// 运算符使用示例 +void main() { + basicDemo(); + + specialDemo(); +} + +// 通用的运算符的使用 +void basicDemo() { + // 声明几个变量 + int a = 5; + var b = 6.0; + bool flag = false; + bool flag2 = true; + + Test demo = new Test(); // 这里会调用Test构造函数 + Test2 demo2 = new Test2(); // 这里会先调用Test构造函数,再调用Test2构造函数 + + print(a++); // 5 + print(b--); // 6.0 + // 构造函数 Test + // Instance of 'Test' + print(new Test()); + var c = const [1, 2]; + print(c); // [1, 2] + print(Test.fun()); // Test fun函数 + + print(5 - 2); // 3 + print(!flag); // true + print(~a); // -7 + print(++a); // 7 + print(--b); // 4.0 + + print(5 * 2); // 10 + print(5 / 2); // 2.5 + print(5 % 2); // 1 + + print(5 + 2); // 7 + print(5 - 2); // 3 + + print(5 >> 2); // 1 + print(5 << 2); // 20 + + print(5 ^ 2); // 7 + print(5 & 2); // 0 + + print(5 | 2); // 7 + + print((5 > 2) && (5 < 2)); // false + print((5 > 2) || (5 < 2)); // true + + print(5 >= 2); // true + print(5 > 2); // true + print(5 <= 2); // false + print(5 < 2); // false + + print(5 == 2); // false + print(5 != 2); // true + + print(a == 3 ? 3 : 2); // 2 + + a = 3; + print(a); // 3 + a *= 3; + print('a *=3 : ${a *= 3}'); // 27 + b /= 3; + print('a /=3 : ${b /= 3}'); // 0.6666666666666666 + a ~/= 3; + print('a ~/=3 : ${a ~/= 3}'); // 3 + a %= 3; + print('a %=3 : ${a %= 3}'); // 0 + a += 3; + print('a +=3 : ${a += 3}'); // 6 + a -= 3; + print('a -=3 : ${a -= 3}'); // 0 + a <<= 3; + print('a <<=3 : ${a <<= 3}'); // 0 + a >>= 3; + print('a >>=3 : ${a >>= 3}'); // 0 + a &= 3; + print('a &=3 : ${a &= 3}'); // 0 + a ^= 3; + print('a ^=3 : ${a ^= 3}'); // 0 + a |= 3; + print('a |=3 : ${a |= 3}'); // 3 +} + +// Dart里面比较有代表性的以及有特点的一些运算符相关用法 +void specialDemo() { + Test test = new Test(); // 这里会调用Test构造函数 + Test2 test2 = new Test2(); // 这里会先调用Test构造函数,再调用Test2构造函数 + + print(Test?.funs); // 先打印null 再打印5 + + String s = (new StringBuffer() + ..write('test1 ') + ..write('test2 ') + ..write('test3 ') + ..write('test4 ') + ..write('test5')) + .toString(); + print(s); // test1 test2 test3 test4 test5 + + int a = 10; + //普通三元运算符 + // var values = a > 5 ? a : 0; + //??操作符 + print('a??3 : 结果是 ${a??3}'); // a ??3 结果是 10 + + var values = (a != 0) ? a : 0; + print('values=${values}'); // values=10 + + var result2 = 5 / 2; + print(result2); //结果是:2.5 + var result3 = 5 ~/ 2; + print(result3); //结果是:2 + + print(test2 is Test); // true + print(test is! Test2); // true + + (test2 as Test2).fun(); // Test2 fun函数 + // 相当于 + // if (test2 is Test) { + // test2.fun(); + // } +} + +class Test { + static int funs = 5; + + Test() { + print('构造函数 Test'); + } + static fun() { + print('Test fun函数'); + } +} + +class Test2 extends Test { + Test2() { + print('构造函数 Test2'); + } + void fun() { + print('Test2 fun函数'); + } +} diff --git a/projects/dart_demo/test/6-control_flow_statements/6-1-if_else/if_else_demo.dart b/projects/dart_demo/test/6-control_flow_statements/6-1-if_else/if_else_demo.dart new file mode 100644 index 0000000..4486144 --- /dev/null +++ b/projects/dart_demo/test/6-control_flow_statements/6-1-if_else/if_else_demo.dart @@ -0,0 +1,17 @@ +void main() { + + String text; + int number = 50; + String urlString = 'http://www.baidu.com/'; + + // 确保变量具有非空值 + assert(text != null); + // 确保值小于100 + assert(number < 100); + // 确保这是一个 https 网址 + assert(urlString.startsWith('https')); + + // 要将消息附加到断言,请添加一个字符串作为第二个参数。 + assert(urlString.startsWith('https'), + 'URL ($urlString) should start with "https".'); +} diff --git a/projects/dart_demo/test/6-control_flow_statements/6-2-for/for_demo1.dart b/projects/dart_demo/test/6-control_flow_statements/6-2-for/for_demo1.dart new file mode 100644 index 0000000..c203809 --- /dev/null +++ b/projects/dart_demo/test/6-control_flow_statements/6-2-for/for_demo1.dart @@ -0,0 +1,11 @@ +void main() { + for (int i = 0; i < 10; i++) { + print(i); + } + +// for循环内部的闭包获取索引的值。 + var array = []; + for (var i = 0; i < 10; i++) { + array.add(() => print(i)); + } +} diff --git a/projects/dart_demo/test/6-control_flow_statements/6-2-for/for_demo2.dart b/projects/dart_demo/test/6-control_flow_statements/6-2-for/for_demo2.dart new file mode 100644 index 0000000..6157882 --- /dev/null +++ b/projects/dart_demo/test/6-control_flow_statements/6-2-for/for_demo2.dart @@ -0,0 +1,4 @@ +void main() { + var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]; + numbers.forEach((number)=> print(number)); +} diff --git a/projects/dart_demo/test/6-control_flow_statements/6-2-for/for_demo3.dart b/projects/dart_demo/test/6-control_flow_statements/6-2-for/for_demo3.dart new file mode 100644 index 0000000..7e2982b --- /dev/null +++ b/projects/dart_demo/test/6-control_flow_statements/6-2-for/for_demo3.dart @@ -0,0 +1,6 @@ +void main() { + var list = [1, 2, 3]; + for (var data in list) { + print(data); + } +} diff --git a/projects/dart_demo/test/6-control_flow_statements/6-2-for/for_demo4.dart b/projects/dart_demo/test/6-control_flow_statements/6-2-for/for_demo4.dart new file mode 100644 index 0000000..0ae7872 --- /dev/null +++ b/projects/dart_demo/test/6-control_flow_statements/6-2-for/for_demo4.dart @@ -0,0 +1,209 @@ +import 'dart:math'; + +void main() { + test1(); + test2(); + test3(); + test4(); + test5(); + test6(); +} + +test1() { + // 返回具有最小总和的内部列表(正整数)。 + /// Returns the inner list (of positive integers) with the smallest sum. + List smallestSumList(List> lists) { + var smallestSum = 0xFFFFFFFF; //已知list的总和较小。 + var smallestList = null; + outer: // 这就是标记 + for (var innerList in lists) { + var sum = 0; + for (var element in innerList) { + assert(element >= 0); + sum += element; + // 无需继续迭代内部列表。它的总和已经太高了。 + if (sum > smallestSum) continue outer; // continue 跳出到标记处(outer) + } + smallestSum = sum; + smallestList = innerList; + } + return smallestList; + } +} + +test2() { + // 计算第一个非空list + List firstListWithNullValueList(List> lists) { + var firstListWithNullValues = null; + outer: + for (var innerList in lists) { + for (var element in innerList) { + if (element == null) { + firstListWithNullValues = innerList; + break outer; // break 返回到标记处 + } + } + } + // 现在继续正常的工作流程 + if (firstListWithNullValues != null) { + // ... + } + return firstListWithNullValues; + } +} + +test3() { + void doSomethingWithA(A a) { + errorChecks: + { + if (a.hasEntries) { + for (var entry in a.entries) { + if (entry is Bad) break errorChecks; // 跳出代码块 + } + } + if (a.hasB) { + var b = new A.b(); + if (b.inSomeBadState()) break errorChecks; // 跳出代码块 + } + // 一些看起来都正常 + use(a); + return; + } + // 错误的情况,执行这里的代码: + print("something bad happened"); + } +} + +// 这两者是对等的 +test4() { + // 使用 continue + for (int i = 0; i < 10; i++) { + if (i.isEven) continue; + print(i); + } + +// 使用 break. + for (int i = 0; i < 10; i++) { + labels: + { + // isEven 当且仅当该整数为偶数时才返回true + if (i.isEven) break labels; + print(i); + } + } +} + +test5() { + void switchExample(int foo) { + switch (foo) { + case 0: + print("foo is 0"); + break; + case 1: + print("foo is 1"); + continue shared; // Continue使用在被标记为shared的子句中 + shared: + case 2: + print("foo is either 1 or 2"); + break; + } + } +} + +test6() { + int age = 0; + int hungry = 0; + int tired = 0; + + bool seesSquirrel() => new Random().nextDouble() < 0.1; + bool seesMailman() => new Random().nextDouble() < 0.1; + + switch (1) { + start: + case 0: + print("dog 方法已经开始"); + print('case 0 ==> age: $age'); + print('case 0 ==> hungry: $hungry'); + print('case 0 ==> tired: $tired'); + continue doDogThings; + + sleep: + case 1: + print("sleeping"); + tired = 0; + age++; + if (age > 20) break; + print('case 1 ==> age: $age'); + print('case 1 ==> hungry: $hungry'); + print('case 1 ==> tired: $tired'); + continue doDogThings; + + doDogThings: + case 2: + if (hungry > 2) continue eat; + if (tired > 3) continue sleep; + if (seesSquirrel()) continue chase; + if (seesMailman()) continue bark; + print('case 2 ==> age: $age'); + print('case 2 ==> hungry: $hungry'); + print('case 2 ==> tired: $tired'); + continue play; + + chase: + case 3: + print("chasing"); + hungry++; + tired++; + print('case 3 ==> age: $age'); + print('case 3 ==> hungry: $hungry'); + print('case 3 ==> tired: $tired'); + continue doDogThings; + + eat: + case 4: + print("eating"); + hungry = 0; + print('case 4 ==> age: $age'); + print('case 4 ==> hungry: $hungry'); + print('case 4 ==> tired: $tired'); + continue doDogThings; + + bark: + case 5: + print("barking"); + tired++; + print('case 5 ==> age: $age'); + print('case 5 ==> hungry: $hungry'); + print('case 5 ==> tired: $tired'); + continue doDogThings; + + play: + case 6: + print("playing"); + tired++; + hungry++; + print('case 6 ==> age: $age'); + print('case 6 ==> hungry: $hungry'); + print('case 6 ==> tired: $tired'); + continue doDogThings; + } +} + +class A { + bool hasEntries = false; + bool hasB = true; + List entries = [new Bad2(), new Bad2()]; + A.b() {} + + bool inSomeBadState() { + return false; + } +} + +void use(A a) {} + +abstract class Bad {} + +class Bad1 extends Bad {} + +class Bad2 extends Bad {} diff --git a/projects/dart_demo/test/6-control_flow_statements/6-3-while&do_while/while_demo.dart b/projects/dart_demo/test/6-control_flow_statements/6-3-while&do_while/while_demo.dart new file mode 100644 index 0000000..256103f --- /dev/null +++ b/projects/dart_demo/test/6-control_flow_statements/6-3-while&do_while/while_demo.dart @@ -0,0 +1,10 @@ +void main() { + int a = 10; + while (a > 5) { + print(a); + } + + do { + print(a); + } while (a > 5); +} diff --git a/projects/dart_demo/test/6-control_flow_statements/6-4-break&continue/break&continue_demo.dart b/projects/dart_demo/test/6-control_flow_statements/6-4-break&continue/break&continue_demo.dart new file mode 100644 index 0000000..91520ec --- /dev/null +++ b/projects/dart_demo/test/6-control_flow_statements/6-4-break&continue/break&continue_demo.dart @@ -0,0 +1,17 @@ +void main() { + int a = 10; + int b = 15; + while (a > 5) { + if (b > 5) { + print(a); + break; + } + } + + while (a > 5) { + if (b < 10) { + print(b); + continue; + } + } +} diff --git a/projects/dart_demo/test/6-control_flow_statements/6-5-switch&case/switch_case_demo.dart b/projects/dart_demo/test/6-control_flow_statements/6-5-switch&case/switch_case_demo.dart new file mode 100644 index 0000000..726d84c --- /dev/null +++ b/projects/dart_demo/test/6-control_flow_statements/6-5-switch&case/switch_case_demo.dart @@ -0,0 +1,29 @@ +void main() { + var command = 'OPEN'; + switch (command) { + case 'CLOSED': + executeClosed(); + break; + case 'PENDING': + executePending(); + break; + case 'APPROVED': + executeApproved(); + break; + case 'DENIED': + executeDenied(); + break; + case 'OPEN': + executeOpen(); + break; + default: + executeUnknown(); + } +} + +executeClosed(){} +executePending(){} +executeApproved(){} +executeDenied(){} +executeOpen(){} +executeUnknown(){} \ No newline at end of file diff --git a/projects/dart_demo/test/6-control_flow_statements/6-6-assert/assert_demo.dart b/projects/dart_demo/test/6-control_flow_statements/6-6-assert/assert_demo.dart new file mode 100644 index 0000000..e69de29 diff --git a/projects/dart_demo/test/7-exception/exception_demo.dart b/projects/dart_demo/test/7-exception/exception_demo.dart new file mode 100644 index 0000000..38492f6 --- /dev/null +++ b/projects/dart_demo/test/7-exception/exception_demo.dart @@ -0,0 +1,74 @@ +void main() { + test1('a123'); + test2(); + test3(); + misbehave(); + test4(); + + try { + misbehave(); + } catch (e) { + print('main() finished handling ${e.runtimeType}.'); + } +} + +void test1(String num) { + if (num.startsWith('a')) { + print(num); + } else { + throw FormatException('格式化错误'); + } +} + +void test2() => throw FormatException('格式化错误'); + +test3() { +// try { +// breedMoreLlamas(); +// } on Exception { +// buyMoreLlamas(); +// } + +// 也可以两个参数的catch + try { + // ··· + } on Exception catch (e) { + print('Exception details:\n $e'); + } catch (e, s) { + print('Exception details:\n $e'); + print('Stack trace:\n $s'); + } +} + +breedMoreLlamas() {} +buyMoreLlamas() {} +cleanLlamaStalls() {} + +void misbehave() { + try { + dynamic foo = true; + print(foo++); // 运行时异常 + } catch (e) { + print('misbehave() partially handled ${e.runtimeType}.'); + rethrow; // 允许调用者查看exception. + } +} + +test4() { + try { + breedMoreLlamas(); + } finally { + // 即使抛出异常 也会执行这句代码. + cleanLlamaStalls(); + } +// 该finally子句在任何匹配的catch子句之后运行: + try { + breedMoreLlamas(); + } catch (e) { + // 首先会处理异常 + print('Error: $e'); + } finally { + // 然后执行这句语句 + cleanLlamaStalls(); + } +} diff --git a/projects/dart_demo/test/8-class/1-class-type/1-common-class/1-common_class.dart b/projects/dart_demo/test/8-class/1-class-type/1-common-class/1-common_class.dart new file mode 100644 index 0000000..8967480 --- /dev/null +++ b/projects/dart_demo/test/8-class/1-class-type/1-common-class/1-common_class.dart @@ -0,0 +1,7 @@ +// 普通类 +void main(){ + new Test().tests(); +} +class Test{ + void tests(){} +} \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/1-class-type/1-common-class/2-object_type.dart b/projects/dart_demo/test/8-class/1-class-type/1-common-class/2-object_type.dart new file mode 100644 index 0000000..cbb5961 --- /dev/null +++ b/projects/dart_demo/test/8-class/1-class-type/1-common-class/2-object_type.dart @@ -0,0 +1,20 @@ +// 对象类型 +void main(){ + var a = 10; + var b = 10.0; + var c = '10'; + var d = true; + var e = [12.5,13.1]; + var f = {3:'5',5:'11'}; + var t = new Test(); + print('a 的类型是: ${a.runtimeType}'); // a 的类型是: int + print('b 的类型是: ${b.runtimeType}'); // b 的类型是: double + print('c 的类型是: ${c.runtimeType}'); // c 的类型是: String + print('d 的类型是: ${d.runtimeType}'); // d 的类型是: bool + print('e 的类型是: ${e.runtimeType}'); // e 的类型是: List + print('f 的类型是: ${f.runtimeType}'); // f 的类型是: _InternalLinkedHashMap + print('t 的类型是: ${t.runtimeType}'); // t 的类型是: Test + +} +class Test{ +} \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/1-class-type/1-common-class/3-exdtend_a_class/3-extends_demo.dart b/projects/dart_demo/test/8-class/1-class-type/1-common-class/3-exdtend_a_class/3-extends_demo.dart new file mode 100644 index 0000000..ba873d9 --- /dev/null +++ b/projects/dart_demo/test/8-class/1-class-type/1-common-class/3-exdtend_a_class/3-extends_demo.dart @@ -0,0 +1,29 @@ +// 继承一个类 示例代码 +class Test { + void test() { + print('Test ==> test()'); + } + // ··· +} + +class TestChild extends Test { + // @override标注在test()函数上面 表示test()函数是重写父类的 + @override + void test() { + super.test(); + print('TestChild ==> test()'); + } + // ··· +} + +// @deprecated的使用 表示过时方法 +class Television { + @deprecated + void activate() { + turnOn(); + } + + void turnOn() { + //... + } +} \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/1-class-type/1-common-class/3-exdtend_a_class/4-annotation_demo.dart b/projects/dart_demo/test/8-class/1-class-type/1-common-class/3-exdtend_a_class/4-annotation_demo.dart new file mode 100644 index 0000000..9e5c2c1 --- /dev/null +++ b/projects/dart_demo/test/8-class/1-class-type/1-common-class/3-exdtend_a_class/4-annotation_demo.dart @@ -0,0 +1,8 @@ +// 定义元数据 +library todo; + +class Todo { + final String who; + final String what; + const Todo(this.who, this.what); +} \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/1-class-type/1-common-class/3-exdtend_a_class/5-annotation_use.dart b/projects/dart_demo/test/8-class/1-class-type/1-common-class/3-exdtend_a_class/5-annotation_use.dart new file mode 100644 index 0000000..2e28c4f --- /dev/null +++ b/projects/dart_demo/test/8-class/1-class-type/1-common-class/3-exdtend_a_class/5-annotation_use.dart @@ -0,0 +1,11 @@ +import '4-annotation_demo.dart'; + +void main(){ + doSomething(); +} + +// 以下是使用@todo注释的示例: +@Todo('seth', 'make this do something') +void doSomething() { + print('do something'); +} \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/1-class-type/1-common-class/4-static_variable.dart b/projects/dart_demo/test/8-class/1-class-type/1-common-class/4-static_variable.dart new file mode 100644 index 0000000..25c4786 --- /dev/null +++ b/projects/dart_demo/test/8-class/1-class-type/1-common-class/4-static_variable.dart @@ -0,0 +1,20 @@ + +// 静态变量和方法 +void main() { + assert(Test. a == 16); + print(Point.area(5, 4)); +} + +// 静态变量 +class Test { + static const num a = 16; + // ··· +} + + +// 静态方法 +class Point { + static num area(num x, num y) { + return (x * y)/2; + } +} \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/1-class-type/1-common-class/5-operator_demo.dart b/projects/dart_demo/test/8-class/1-class-type/1-common-class/5-operator_demo.dart new file mode 100644 index 0000000..fe5005d --- /dev/null +++ b/projects/dart_demo/test/8-class/1-class-type/1-common-class/5-operator_demo.dart @@ -0,0 +1,41 @@ +////// 重写运算符 /////// + +void main() { + final a = Testoperator(2, 3); + final b = Testoperator(2, 2); + var num1 = Testoperator(4, 5); + var num2= Testoperator(0,1); + print(a + b == num1); // true + print(a - b == num2); // true + +} + +////// 重写+ 和 - 运算符 /////// +class Testoperator { + final int x, y; + + Testoperator(this.x, this.y); + + Testoperator operator +(Testoperator o) => Testoperator(x + o.x, y + o.y); + Testoperator operator -(Testoperator o) => Testoperator(x - o.x, y - o.y); + + // Operator == and hashCode not shown. For details, see note below. + // ··· + + // Override hashCode using strategy from Effective Java, Chapter 11. + @override + int get hashCode { + int result = 17; + result = 37 * result + x.hashCode; + result = 37 * result + y.hashCode; + return result; + } + + // You should generally implement operator == if you override hashCode. + @override + bool operator ==(dynamic other) { + if (other is! Testoperator) return false; + Testoperator person = other; + return (person.x == x && person.y == y); + } +} \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/1-class-type/1-common-class/6-nosuchmethod_demo.dart b/projects/dart_demo/test/8-class/1-class-type/1-common-class/6-nosuchmethod_demo.dart new file mode 100644 index 0000000..2967bfb --- /dev/null +++ b/projects/dart_demo/test/8-class/1-class-type/1-common-class/6-nosuchmethod_demo.dart @@ -0,0 +1,20 @@ +/////////// 重写 noSuchMethod //////////////// + +void main() { + TestMethod test = new TestMethod(); + dynamic f = test.foo; + // Invokes `Object.noSuchMethod`, not `TestMethod.noSuchMethod`, so it throws. + f(42); +} + + +class TestMethod { + // 除非你重写noSuchMethod,否则使用不存在的成员会导致NoSuchMethodError + @override + dynamic noSuchMethod(Invocation i) { + print('You tried to use a non-existent member: ' + + '${i.memberName}'); + } + + dynamic foo(); +} \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/1-class-type/2-abstract_class/1-abstract_demo.dart b/projects/dart_demo/test/8-class/1-class-type/2-abstract_class/1-abstract_demo.dart new file mode 100644 index 0000000..efc919e --- /dev/null +++ b/projects/dart_demo/test/8-class/1-class-type/2-abstract_class/1-abstract_demo.dart @@ -0,0 +1,7 @@ +// 此类声明为abstract,因此无法实例化 +abstract class Test { + //定义构造函数,字段,方法... + + // 抽象方法 + void test(); +} \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/1-class-type/2-abstract_class/2-abstract_demo.dart b/projects/dart_demo/test/8-class/1-class-type/2-abstract_class/2-abstract_demo.dart new file mode 100644 index 0000000..9d11043 --- /dev/null +++ b/projects/dart_demo/test/8-class/1-class-type/2-abstract_class/2-abstract_demo.dart @@ -0,0 +1,33 @@ +// 隐式接口 +void main() { + print(sayHello(Person('李四'))); // 你好 张三. 我是 李四. + print(sayHello(PersonImpl())); // 你好 张三 你知道我是谁吗? +} + +// Person类 隐式接口包含hello() +class Person { + // 在接口中,但是仅在此库中可见。 + final _name; + + // 不在接口中,因为这是一个构造函数 + Person(this._name); + + // 在接口中 + String hello(String who) => '你好 $who. 我是 $_name.'; +} + +// Person接口的实现 +class PersonImpl implements Person { + get _name => ''; + + String hello(String name) => '你好 $name 你知道我是谁吗?'; +} + +String sayHello(Person person) => person.hello('张三'); + +// 一个类也可以实现多个接口,例如: +class ZhangSan implements Run,Life { + //... +} +class Run {} +class Life {} \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/1-class-type/3-callable_class/callable_class_demo.dart b/projects/dart_demo/test/8-class/1-class-type/3-callable_class/callable_class_demo.dart new file mode 100644 index 0000000..dd27089 --- /dev/null +++ b/projects/dart_demo/test/8-class/1-class-type/3-callable_class/callable_class_demo.dart @@ -0,0 +1,10 @@ +// 可调用的类(Callable Class) +void main() { + var test = new Test(); + var result = test(166.6665,"Flutter真好玩",672); +print("$result");// 666.666 Flutter真好玩 666 +} +class Test { + // 必须是call函数 + call(double a, String b, int c) => '${a*4} ${b} ${c-6}'; +} \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/1-class-type/4-enum/enum_demo.dart b/projects/dart_demo/test/8-class/1-class-type/4-enum/enum_demo.dart new file mode 100644 index 0000000..c7cbe2f --- /dev/null +++ b/projects/dart_demo/test/8-class/1-class-type/4-enum/enum_demo.dart @@ -0,0 +1,28 @@ +//枚举示例 + +void main() { + // 判断枚举的索引值是多少 + assert(Color.red.index == 0); + print(Color.green.index == 1); + print(Color.blue.index == 2); + + // 获取枚举中所有值的列表 + List colors = Color.values; + print(colors[2] == Color.blue); + + // switch中使用枚举 + var aColor = Color.blue; + switch (aColor) { + case Color.red: + print('Red'); + break; + case Color.green: + print('Green'); + break; + default: // 你没有这个 你会看到一个警告 + print(aColor); // 'Color.blue' + } +} + +// 声明枚举类型 +enum Color { red, green, blue } diff --git a/projects/dart_demo/test/8-class/1-class-type/5-mixin/1-create_mixin.dart b/projects/dart_demo/test/8-class/1-class-type/5-mixin/1-create_mixin.dart new file mode 100644 index 0000000..980dc3c --- /dev/null +++ b/projects/dart_demo/test/8-class/1-class-type/5-mixin/1-create_mixin.dart @@ -0,0 +1,64 @@ +// mixin + + +// 声明mixin + +// 专家 +mixin Expert { + // 发现和解决难题 + bool solveProblems = false; + + // 精通数据结构和算法 + bool dataStructureAndAlgorithms = false; + + // 会架构设计 + bool architectureDesign = false; + + // 性能优化 + bool performanceOptimization = false; + + // 熟练掌握计算机系统 + bool computerSystem = false; + + void develop() { + // 娱乐节目 + if (solveProblems) { + print('发现和解决难题'); + } + if (dataStructureAndAlgorithms) { + print('精通数据结构和算法'); + } + if (architectureDesign) { + print('会架构设计'); + } + if (performanceOptimization) { + print('熟练掌握性能优化'); + } + if (computerSystem) { + print('熟练掌握计算机系统'); + } + } +} + +// 特性 + +// 有效率的 +mixin Efficient { + void getEfficientAttrs() { + print('有效率的'); + } +} + +// 和蔼的 +mixin Kind { + void getKindAttrs() { + print('和蔼的'); + } +} + +// 软件架构师 +class SoftwareArchitect { + SoftwareArchitect() { + print('软件架构师'); + } +} \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/1-class-type/5-mixin/2-use_mixin.dart b/projects/dart_demo/test/8-class/1-class-type/5-mixin/2-use_mixin.dart new file mode 100644 index 0000000..0d480c6 --- /dev/null +++ b/projects/dart_demo/test/8-class/1-class-type/5-mixin/2-use_mixin.dart @@ -0,0 +1,61 @@ +import '1-create_mixin.dart'; + +// 使用mixin + +void main() { + // 姓名:张三 + // 发现和解决难题 + // 精通数据结构和算法 + // 会架构设计 + ACompanySoftwareArchitect architect1 = new ACompanySoftwareArchitect('张三'); + architect1.develop(); + print('===='); + // 姓名:李四 + // 发现和解决难题 + // 精通数据结构和算法 + // 会架构设计 + // 熟练掌握性能优化 + // 熟练掌握计算机系统 + // 有效率的 + // 和蔼的 + BCompanySoftwareArchitect architect2 = new BCompanySoftwareArchitect('李四'); + architect2.develop(); + architect2.getEfficientAttrs(); + architect2.getKindAttrs(); +} + + +// 使用mixin + +// A公司的软件架构师,继承自软件架构师,拥有专家的特性。 +class ACompanySoftwareArchitect extends SoftwareArchitect with Expert { + String name; + ACompanySoftwareArchitect(String name) { + this.name = name; + print('姓名:' + name); + solveProblems = true; + dataStructureAndAlgorithms = true; + architectureDesign = true; + } + + @override + void develop() { + super.develop(); + } +} + +// B公司的软件架构师,继承自软件架构师, +class BCompanySoftwareArchitect extends SoftwareArchitect + with Expert, Efficient, Kind { + String name; + + BCompanySoftwareArchitect(String name) { + this.name = name; + print('姓名:' + name); + solveProblems = true; + dataStructureAndAlgorithms = true; + architectureDesign = true; + performanceOptimization = true; + computerSystem = true; + } +} \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/1-class-type/5-mixin/3-use_mixin2.dart b/projects/dart_demo/test/8-class/1-class-type/5-mixin/3-use_mixin2.dart new file mode 100644 index 0000000..e302d98 --- /dev/null +++ b/projects/dart_demo/test/8-class/1-class-type/5-mixin/3-use_mixin2.dart @@ -0,0 +1,4 @@ +import '2-use_mixin.dart'; + +// 要指定只有某些类型可以使用mixin +mixin SoftwareDeveloper on ACompanySoftwareArchitect{} \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/2-generics/1-why_use_enerics.dart b/projects/dart_demo/test/8-class/2-generics/1-why_use_enerics.dart new file mode 100644 index 0000000..c40dc07 --- /dev/null +++ b/projects/dart_demo/test/8-class/2-generics/1-why_use_enerics.dart @@ -0,0 +1,60 @@ +// 泛型 demo +void main() { + var names = List(); + names.addAll(['Seth', 'Kathy', 'Lars']); + // 报错 The argument type 'int' can't be assigned to the parameter type 'String'. + // names.add(42); + + // 使用泛型以前的调用方式 + print(new Test1().getByKey('123')); + print(new Test2().getByKey('456')); + // 使用泛型之后的调用方式 +} + +// 使用泛型以前 +abstract class ObjectCache { + Object getByKey(String key); + void setByKey(String key, Object value); +} + +abstract class StringCache { + String getByKey(String key); + void setByKey(String key, String value); +} + +class Test1 extends ObjectCache { + @override + Object getByKey(String key) { + return 'object cache'; + } + + @override + void setByKey(String key, Object value) { + return null; + } +} + +class Test2 extends StringCache { + @override + String getByKey(String key) { + return 'String cache'; + } + + @override + void setByKey(String key, String value) { + return null; + } +} + +// 使用泛型来减少代码重复 +abstract class Cache { + T getByKey(T key); +} + +class Test3 extends Cache { + @override + String getByKey(String key) { + // TODO: implement getByKey + return null; + } +} diff --git a/projects/dart_demo/test/8-class/2-generics/2-use_list.dart b/projects/dart_demo/test/8-class/2-generics/2-use_list.dart new file mode 100644 index 0000000..4e5433b --- /dev/null +++ b/projects/dart_demo/test/8-class/2-generics/2-use_list.dart @@ -0,0 +1,10 @@ +// 泛型 demo +// list或map中使用泛型 +void main() { + var numbers = ['11', '22', '33']; + var pages = { + 'index.html': 'Homepage', + 'store.html': 'Store', + 'mine.html': 'Mine' + }; +} \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/2-generics/3-with-constructor_params.dart b/projects/dart_demo/test/8-class/2-generics/3-with-constructor_params.dart new file mode 100644 index 0000000..d1a6851 --- /dev/null +++ b/projects/dart_demo/test/8-class/2-generics/3-with-constructor_params.dart @@ -0,0 +1,11 @@ +// 泛型 demo +// 使用带有构造函数的参数化类型 +void main() { + var names = List(); + names.addAll(['Seth', 'Kathy', 'Lars']); + + // Set类带有一个泛型 from是一个工厂函数 + // abstract class Set extends EfficientLengthIterable + // factory Set.from(Iterable elements) = LinkedHashSet.from; + var nameSet = Set.from(names); +} diff --git a/projects/dart_demo/test/8-class/2-generics/4-generis_list.dart b/projects/dart_demo/test/8-class/2-generics/4-generis_list.dart new file mode 100644 index 0000000..c9799d4 --- /dev/null +++ b/projects/dart_demo/test/8-class/2-generics/4-generis_list.dart @@ -0,0 +1,8 @@ +// 泛型 demo +// 泛型集合及其包含的类型 +void main() { + var names = List(); + names.addAll(['Seth', 'Kathy', 'Lars']); + print(names is List);// true + print(names.runtimeType);// List +} diff --git a/projects/dart_demo/test/8-class/2-generics/5-limit_params_type.dart b/projects/dart_demo/test/8-class/2-generics/5-limit_params_type.dart new file mode 100644 index 0000000..10a1949 --- /dev/null +++ b/projects/dart_demo/test/8-class/2-generics/5-limit_params_type.dart @@ -0,0 +1,34 @@ +// 泛型 demo +// 限制参数类型 +void main() { + var someBaseClassFoo = Foo(); + var extenderFoo = Foo(); + + print(someBaseClassFoo.toString());// Instance of Foo + print(extenderFoo.toString());// Instance of Foo + + // 不指定泛型参数也可以使用。 + var foo = Foo(); + print(foo); // Instance of 'Foo' + //等同于print(foo.toString()); + print(foo.toString()); // Instance of 'Foo' + + // 如果指定任何非SomeBaseClass类型会导致错误。 + // var foo2 = Foo; + + +} + +abstract class SomeBaseClass { + // 其他操作 +} + +class Foo { + String toString() { + return "Instance of Foo<$T>"; + } +} + +class Extender extends SomeBaseClass { + //其他操作 +} diff --git a/projects/dart_demo/test/8-class/2-generics/6-generis_methods.dart b/projects/dart_demo/test/8-class/2-generics/6-generis_methods.dart new file mode 100644 index 0000000..5c4a1d5 --- /dev/null +++ b/projects/dart_demo/test/8-class/2-generics/6-generis_methods.dart @@ -0,0 +1,31 @@ +// 泛型 demo +// 泛型方法:使用在类和方法上 +void main() { + List data = ["张三","李四","王五"]; + var result = first(data); + print(result); +} + +// 在以下几个地方使用类型参数T: +// 返回类型T, 参数类型List, 局部变量的类型T tmp +T first(List data) { + // 做一些初始工作或错误检查... + T tmp = data[0]; + // 做一些额外的检查或处理... + return tmp; +} + +class Test { + static int first(int x) => 3; + int second(int y) => 5; +} + +void functionTypedParameter(T callback){} + +void localFunction(){ + T itself(T thing) => thing; +} + +void functionExpression(){ + var lambda = (T thing) => thing; +} diff --git a/projects/dart_demo/test/8-class/3-functions/1-common_functions/1-method_write.dart b/projects/dart_demo/test/8-class/3-functions/1-common_functions/1-method_write.dart new file mode 100644 index 0000000..d143780 --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/1-common_functions/1-method_write.dart @@ -0,0 +1,29 @@ +// 函数的简写 + +// 1.对于只有一个表达式的函数,可以简写 +// 操作前: +// void main(){ +// runApp(new MyApp()); +// } +// 操作后:(main.dart文件里面默认使用的是==>箭头符号) +// 箭头符号 +// void main() => runApp(new MyApp()); + +// 2. 返回值为void时,可以省略void关键字 +void main() { + + // 函数属于Funtion类型 + assert(_incrementCounter() is Function); +} + +// 省略前 +// void _incrementCounter() { + //TODO:... +// } + +// 省略后 +_incrementCounter() { + //TODO:... +} + + diff --git a/projects/dart_demo/test/8-class/3-functions/1-common_functions/10-method_abstract.dart b/projects/dart_demo/test/8-class/3-functions/1-common_functions/10-method_abstract.dart new file mode 100644 index 0000000..dca5d6e --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/1-common_functions/10-method_abstract.dart @@ -0,0 +1,15 @@ +// 抽象方法示例 + +abstract class Test { + //定义实例变量和方法... + +//定义一个抽象方法 +void doSomething(); +} + +class TestImpl extends Test { + // 抽象方法的实现 + void doSomething(){ + // 具体的实现... + } +} \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/3-functions/1-common_functions/11-method_static.dart b/projects/dart_demo/test/8-class/3-functions/1-common_functions/11-method_static.dart new file mode 100644 index 0000000..87740b3 --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/1-common_functions/11-method_static.dart @@ -0,0 +1,10 @@ +// 静态方法 +void main() { + print(Point.area(5, 4)); // 10 +} + +class Point { + static num area(num x, num y) { + return (x * y) / 2; + } +} diff --git a/projects/dart_demo/test/8-class/3-functions/1-common_functions/2-choosable_functuons/method_choosable.dart b/projects/dart_demo/test/8-class/3-functions/1-common_functions/2-choosable_functuons/method_choosable.dart new file mode 100644 index 0000000..0ac5c20 --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/1-common_functions/2-choosable_functuons/method_choosable.dart @@ -0,0 +1,29 @@ + +// 可选参数使用: +void main() { + + + // 普通参数使用: + + //你随意使用其中的参数都是可以的,例如我使用了其中的参数1,参数4和参数5 + work2(address:'hangzhou', workTime:'9:00-5:00', workerNumbers:500); + + // 可选参数使用: + + // 缺一个参数都会报错 + work('hangzhou','XXCompany',1000000.00,'9:00-5:00',500); +} + + + +// 工作:地址、公司名、工资、工作时长、公司人数 +void work(String address, String cpompany, double money, String workTime, + int workerNumbers) { + //TODO:... +} + +// 设置了可选参数 +void work2({String address, String cpompany, double money, String workTime, + int workerNumbers}) { + //TODO:... +} \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/3-functions/1-common_functions/2-choosable_functuons/method_choosable2.dart b/projects/dart_demo/test/8-class/3-functions/1-common_functions/2-choosable_functuons/method_choosable2.dart new file mode 100644 index 0000000..3324291 --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/1-common_functions/2-choosable_functuons/method_choosable2.dart @@ -0,0 +1,9 @@ +// 可选参数的默认值 +void work3( + {String address = 'hangzhou', + String cpompany = ' XXCompany ', + double money, + String workTime, + int workerNumbers}) { + //TODO:... +} diff --git a/projects/dart_demo/test/8-class/3-functions/1-common_functions/2-choosable_functuons/method_choosable3.dart b/projects/dart_demo/test/8-class/3-functions/1-common_functions/2-choosable_functuons/method_choosable3.dart new file mode 100644 index 0000000..5c0390c --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/1-common_functions/2-choosable_functuons/method_choosable3.dart @@ -0,0 +1,8 @@ +// 普通函数的参数是一个匿名List集合,使用 = 设置默认值,比如address默认值为'hangzhou' +void work4(String address, + [String cpompany = ' XXCompany ', + double money, + String workTime, + int workerNumbers]) { + //TODO:... +} diff --git a/projects/dart_demo/test/8-class/3-functions/1-common_functions/2-choosable_functuons/method_choosable4.dart b/projects/dart_demo/test/8-class/3-functions/1-common_functions/2-choosable_functuons/method_choosable4.dart new file mode 100644 index 0000000..c608a63 --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/1-common_functions/2-choosable_functuons/method_choosable4.dart @@ -0,0 +1,10 @@ +// 可变参数可以是显示声明的List集合或者map +void work5( + {List list = const [10, 20, 30], + Map gifts = const { + 'cpompany': 'XXCompany', + 'money': '50000', + 'workTime': '9:00-5:00', + }}) { + //TODO:... +} diff --git a/projects/dart_demo/test/8-class/3-functions/1-common_functions/3-method_params.dart b/projects/dart_demo/test/8-class/3-functions/1-common_functions/3-method_params.dart new file mode 100644 index 0000000..c5a9b39 --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/1-common_functions/3-method_params.dart @@ -0,0 +1,12 @@ +// 函数作为参数穿个另一个函数 +void main() { + // 例如main.dart里面FloatingActionButton的onPressed参数引入了一个_incrementCounter()函数 + // floatingActionButton: new FloatingActionButton(onPressed: _incrementCounter,), +} + + +void _incrementCounter() { +// setState(() { +// _counter++; +// }); +} \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/3-functions/1-common_functions/4-method_noname.dart b/projects/dart_demo/test/8-class/3-functions/1-common_functions/4-method_noname.dart new file mode 100644 index 0000000..1092d96 --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/1-common_functions/4-method_noname.dart @@ -0,0 +1,17 @@ +// 匿名函数 +void main() { + void _incrementCounter() { + //setState函数就用到了匿名函数 +// setState(() { +// _counter++; +// }); + } + + // + List list = [10, 7, 23]; + list.forEach((item) { + print('$item'); + }); + + list.forEach((item) => print('$item')); +} \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/3-functions/1-common_functions/5-method_resolution.dart b/projects/dart_demo/test/8-class/3-functions/1-common_functions/5-method_resolution.dart new file mode 100644 index 0000000..2457322 --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/1-common_functions/5-method_resolution.dart @@ -0,0 +1,48 @@ +// 语法作用域 + +bool topLevel = true; + +void main() { + var insideMain = true; + + void myFunction() { + var insideFunction = true; + + void nestedFunction() { + var insideNestedFunction = true; + + print('topLevel\r'); + print(topLevel); + print('insideMain\r'); + print(insideMain); + print('insideFunction\r'); + print(insideFunction); + print('insideNestedFunction\r'); + print(insideNestedFunction); + } + + // print('topLevel\r'); + // print(topLevel); + // print('insideMain\r'); + // print(insideMain); + // print('insideFunction\r'); + // print(insideFunction); + + // 调用函数nestedFunction + nestedFunction(); + + } + + // 调用函数myFunction + myFunction(); + + // print('topLevel\r'); + // print(topLevel); + // print('insideMain\r'); + // print(insideMain); +} + +//函数只能打印它的外层以及它里面的变量,前提是要被调用 +// main函数里面可以输出topLevel和insideMain的值。 +// myFunction函数里面可以输出topLevel、insideMain和insideFunction的值。 +// nestedFunction函数里面可以输出topLevel、insideMain、insideFunction和insideNestedFunction的值。 \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/3-functions/1-common_functions/6-method_closure.dart b/projects/dart_demo/test/8-class/3-functions/1-common_functions/6-method_closure.dart new file mode 100644 index 0000000..840505e --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/1-common_functions/6-method_closure.dart @@ -0,0 +1,33 @@ +// 借鉴js的闭包的5种方式 来聊聊闭包在Dart中的使用 +void main() { + var result = test(); + print(result(2.0)); + // 变量作用域为函数内部,外部无法访问 + // print(result.PI); + + //外部要访问方法内部的变量,可以使用闭包 + var result2 = test2(); + print(result2()); +} + +//js闭包写法 +// var Circle = new Function( +// "this.PI = 3.14; +// this.area = function( r ) { +// return r*r*this.PI; +// }" +// ); + +// 转换成Dart语言就是这样的: +// 内部函数为有参数的匿名函数示例: +Function test() { + const PI = 3.14; + return (double r) => r * r * PI; +} + +// 内部函数为无参数的匿名函数示例: +Function test2() { + const PI = 3.14; + return () => PI; +} + diff --git a/projects/dart_demo/test/8-class/3-functions/1-common_functions/7-method_equals.dart b/projects/dart_demo/test/8-class/3-functions/1-common_functions/7-method_equals.dart new file mode 100644 index 0000000..2c34e3b --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/1-common_functions/7-method_equals.dart @@ -0,0 +1,32 @@ +//函数也是对象 + +void topMethod() {} // 一个顶级函数 + +class Demo { + static void staticMethod() {} //一个静态方法 + void caseMethod() {} //实例方法 +} + +void main() { + var compareVar; + + // 比较顶级的函数 + compareVar = topMethod; + print(topMethod == compareVar); + + // 比较静态方法 + compareVar = Demo.staticMethod; + print(Demo.staticMethod == compareVar); + + // 比较实例方法 + var demo1 = Demo(); // Demo类的实例1 + var demo2 = Demo(); // Demo类的实例2 + var y = demo2; + compareVar = demo2.caseMethod; + + //这些闭包指向同一个实例demo2,所以它们相等。 + print(y.caseMethod == compareVar); + + //这些闭包是指不同的实例,所以他们不平等。 + print(demo1.caseMethod != demo2.caseMethod); +} \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/3-functions/1-common_functions/8-method_alias.dart b/projects/dart_demo/test/8-class/3-functions/1-common_functions/8-method_alias.dart new file mode 100644 index 0000000..33eb2aa --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/1-common_functions/8-method_alias.dart @@ -0,0 +1,42 @@ +// 当看到用typedef定义函数别名的时候,不自觉的想到了函数指针 + +void main(){ + + // 3. main函数里面使用Demo类,给mFunction参数传入一个函数 + + int test(Object a, Object b) => 0; + + Demo demo = Demo(test); + print(demo.funs is Function); // true + print(demo.funs is Demo); // false + +} + + +// 1.给Function取一个别名叫做TypedefFuns +typedef TypedefFuns = int Function(Object a, Object b); + + +// 2. Demo类里的构造方法使用这个别名 +class Demo { + TypedefFuns funs; + Demo(this.funs); +} + + + + +// Flutter源码FloatingActionButton里面的typedef使用 +// final VoidCallback onPressed; + +// class FloatingActionButton{ +// const FloatingActionButton({this.onPressed,String name}); +// } + +// get set可以不要 +// VoidCallback get onMetricsChanged => _onMetricsChanged; +// VoidCallback _onMetricsChanged; + +// set onMetricsChanged(VoidCallback callback) { +// _onMetricsChanged = callback; +// } diff --git a/projects/dart_demo/test/8-class/3-functions/1-common_functions/9-get_and_set/get_set_demo1.dart b/projects/dart_demo/test/8-class/3-functions/1-common_functions/9-get_and_set/get_set_demo1.dart new file mode 100644 index 0000000..a217afc --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/1-common_functions/9-get_and_set/get_set_demo1.dart @@ -0,0 +1,18 @@ +// getter setter 测试代码 +void main() { + var rect = Rectangle(3, 4, 20, 15); + print(rect.left == 3); + rect.right = 12; + print(rect.left == -8); +} + +class Rectangle { + num left, top, width, height; + + Rectangle(this.left, this.top, this.width, this.height); + + num get right => left + width; + set right(num value) => left = value - width; + num get bottom => top + height; + set bottom(num value) => top = value - height; +} \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/3-functions/1-common_functions/9-get_and_set/get_set_demo2.dart b/projects/dart_demo/test/8-class/3-functions/1-common_functions/9-get_and_set/get_set_demo2.dart new file mode 100644 index 0000000..047fbde --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/1-common_functions/9-get_and_set/get_set_demo2.dart @@ -0,0 +1,25 @@ + +// 所有实例变量都生成一个隐式getter方法 +// 非final实例变量也会生成隐式setter方法 +void main() { + var point = Point(); + point.x = 4; // Use the setter method for x. + assert(point.x == 4); // Use the getter method for x. + assert(point.y == null); // Values default to null. + + var point2 = Point2(); + point2.x = 4; // +} + + +class Point { + num x; + num y; +} + +class Point2 { + num x = 10; + num y = 5; + Point2 p = new Point2();//p在构造函数之前执行 + Point2(){} +} diff --git a/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/1-constructor_common.dart b/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/1-constructor_common.dart new file mode 100644 index 0000000..d4cc531 --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/1-constructor_common.dart @@ -0,0 +1,15 @@ + +// 最常见的构造函数形式 +void main(){ + new Test(3, 4); // x:3, y:4 +} + +class Test { + num x, y; + + Test(num x, num y) { + this.x = x;//this.x指向的是当前Test类里面的变量num x + this.y = y; + print('x:$x, y:$y'); + } +} \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/2-constructor_params.dart b/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/2-constructor_params.dart new file mode 100644 index 0000000..641b1d7 --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/2-constructor_params.dart @@ -0,0 +1,23 @@ +// Dart具有语法糖,可以将构造函数参数赋值给实例变量 +void main() { + new Test1(3, 4); // x:3, y:4 +} + +class Test1 { + num x, y; + + // 构造函数运行之前设置x和y + Test1(this.x, this.y) { + print('x:$x, y:$y'); + } + + // 没有内容体 可以简写 + // Test1(num x, num y); +} + +class Test2 { + num x, y; + + // 没有内容体 可以简写 + Test2(num x, num y); +} diff --git a/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/3-constructor_default.dart b/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/3-constructor_default.dart new file mode 100644 index 0000000..7739623 --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/3-constructor_default.dart @@ -0,0 +1,13 @@ +// 空参构造 +void main() { + new Test(); +} + +class Test { + + // 如果不写 默认就是空参构造 + Test() { + print('默认构造函数'); + } + +} diff --git a/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/4-constructor_named.dart b/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/4-constructor_named.dart new file mode 100644 index 0000000..f244cfc --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/4-constructor_named.dart @@ -0,0 +1,17 @@ +// 命名构造 +void main() { + new Test.help(); +} + +class Test{ + var x, y; + Test(){ + print('这是 Test 类的空参构造');//Test.help() 命名函数 x=5, y = 10 + } + // 命名构造 + Test.help(){ + x = 5; + y = 10; + print('Test.help() 命名函数 x=${x}, y = ${y}'); + } +} diff --git a/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/5-constructor_not_extends.dart b/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/5-constructor_not_extends.dart new file mode 100644 index 0000000..2c358a1 --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/5-constructor_not_extends.dart @@ -0,0 +1,36 @@ +// 构造不能被继承 +void main() { + // 先执行Test类的空参构造, 再执行TestChild类的空参构造。 + // 这是 Test 类的空参构造 + // 这是 TestChild 类的空参构造 + new TestChild(); + + // 调用时会报错 + // new TestChild.help(); +} + +class Test{ + var x, y; + Test(){ + print('这是 Test 类的空参构造'); + } +// 命名构造不能被继承 + Test.help(){ + x = 5; + y = 10; + print('Test.help() 命名函数 x=${x}, y = ${y}'); + } +} + +class TestChild extends Test{ + var x, y; + TestChild(){ + print('这是 TestChild 类的空参构造'); + } + // 加上与父类相同的命名构造就不会错 注释了就会报错 + // TestChild.help(){ + // x = 3; + // y = 2; + // print('TestChild.help() 命名函数 x=${x}, y = ${y}'); + // } +} diff --git a/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/6-calling-process/calling-process1.dart b/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/6-calling-process/calling-process1.dart new file mode 100644 index 0000000..0c74e1f --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/6-calling-process/calling-process1.dart @@ -0,0 +1,42 @@ +// 构造函数调用流程 +void main() { + // Test 空参构造 + // TestChild 有参构造 + // 面积为:6.0 + var result = new TestChild.area(3, 4); + print('面积为:${result.area}'); +} + +class Test { + num width; + num height; + num area; + + // 必须加上空参构造,如果注释掉 它的子类会报错 + Test() { + print('Test 空参构造'); + } + + Test.area(width, height) + : width = width, + height = height, + area = width * height { + print('Test 有参构造'); + } +} + +class TestChild extends Test { + + num width; + num height; + num area; + + TestChild() { + print('TestChild 空参构造'); + } + + TestChild.area(num width, num height) + : area = (width * height)/2 { + print('TestChild 有参构造'); + } +} \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/6-calling-process/calling-process2.dart b/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/6-calling-process/calling-process2.dart new file mode 100644 index 0000000..cea422f --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/6-calling-process/calling-process2.dart @@ -0,0 +1,27 @@ +void main(){ + // Test.area 命名函数,data: TestChild的数据 getDefaultData + // TestChild 空参函数 调用父类的命名构造 + new TestChild(); +} + +class Test{ + static String data; + Test() { + print('Test 空参构造,data: $data'); + } + + Test.area(String datas) { + print('Test.area 命名函数,data: $datas'); + } +} + +class TestChild extends Test { + // 参数可以是一个表达式 + TestChild() : super.area(getDefaultData()) { + print('TestChild 空参函数 调用父类的命名构造'); + } + + static String getDefaultData(){ + return 'TestChild的数据 getDefaultData'; + } +} \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/6-calling-process/calling-process3.dart b/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/6-calling-process/calling-process3.dart new file mode 100644 index 0000000..b172403 --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/6-calling-process/calling-process3.dart @@ -0,0 +1,43 @@ +// 超类构造参数不能使用this关键字 +class Test { + num width; + num height; + num area; + + // 必须加上空参构造,如果注释掉 它的子类会报错 + Test() { + print('Test 空参构造'); + } + + Test.area(width, height) + : width = width, + height = height, + area = width * height { + print('Test 有参构造'); + } + + // 超类构造参数不能使用this关键字 + // Test.area(this.width, this.height) + // : width = width, + // height = height, + // area = width * height { + // print('Test 命名构造'); + // } + +} + +class TestChild extends Test { + + num width; + num height; + num area; + + TestChild() { + print('TestChild 空参构造'); + } + + TestChild.area(num width, num height) + : area = (width * height)/2 { + print('TestChild 有参构造'); + } +} \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/7-constructor_redirect.dart b/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/7-constructor_redirect.dart new file mode 100644 index 0000000..4c7b06f --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/7-constructor_redirect.dart @@ -0,0 +1,22 @@ +import 'dart:math'; + +// 重定向构造函数 +void main() { + var result = new Test(4, true, '数字', 10); + // abcd分别是:4,true,数字,10 + print('abcd分别是:${result.a},${result.b},${result.c},${result.d}'); +} + +class Test { + num a; + bool b; + String c; + num d; + // 主构造函数 + Test(this.a, this.b, this.c, this.d); + + // 委托给主构造函数 + Test.test1(num x,bool y) : this(x, y,'', 0); + Test.test2(num a,bool b, String c) : this(a, b, c, 0); + Test.test3(num a,bool b, String c,num d) : this(a, b, c, d); +} \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/8-constructor_constant/constructor_constant1.dart b/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/8-constructor_constant/constructor_constant1.dart new file mode 100644 index 0000000..7c47559 --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/8-constructor_constant/constructor_constant1.dart @@ -0,0 +1,13 @@ +import 'dart:math'; + +// 常量构造函数 +void main() { + var result = new Test(4, 10); + print('x:${result.x}, y: ${result.y}'); +} + +class Test { + static final Test origin = const Test(0, 0); + final num x, y; + const Test(this.x, this.y); +} \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/8-constructor_constant/constructor_constant2.dart b/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/8-constructor_constant/constructor_constant2.dart new file mode 100644 index 0000000..ea95398 --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/8-constructor_constant/constructor_constant2.dart @@ -0,0 +1,24 @@ +import 'dart:math'; + +// 常量上下文中的const构造函数 +void main() { +// 这里有很多const关键字 + const pointAndLine = const { + 'point': const [const ImmutablePoint(0, 0)], + 'line': const [const ImmutablePoint(1, 10), const ImmutablePoint(-2, 11)], + }; + +// 只有一个const, 它建立了常量上下文 + const pointAndLine2 = { + 'point': [ImmutablePoint(0, 0)], + 'line': [ImmutablePoint(1, 10), ImmutablePoint(-2, 11)], + }; + + var a = const ImmutablePoint(1, 1); //创建一个常量 + var b = ImmutablePoint(1, 1); // 不创建常量 + assert(!identical(a, b)); // 不是同一个实例 +} + +class ImmutablePoint{ + const ImmutablePoint(int a, int b); +} \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/9-constructor_factory.dart b/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/9-constructor_factory.dart new file mode 100644 index 0000000..b1fd1e3 --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/2-constructor_functions/9-constructor_factory.dart @@ -0,0 +1,75 @@ +// 工厂构造函数 +void main() { + //Test('abc').test(); + + var a = new Test('abc'); + var b = new Test('abc'); + + // 检查两个是否引用的相同的对象 + print(identical(a, b)); // true + + new Test('abc').test(); + + print(new Singleton() == new Singleton()); + print(identical(new Singleton(), new Singleton())); + + // Cat cat = new Animal('cat'); + // Dog dog = new Animal('dog'); + // Animal animal = new Animal('haha'); +} + +class Test { + final String name; + static Map _cache = new Map(); + + factory Test(String name) { + if (_cache.containsKey(name)) { + return _cache[name]; + } else { + final symbol = new Test._internal(name); + _cache[name] = symbol; + return symbol; + } + } + + Test._internal(this.name); + + void test(){ + print('调用了test()'); + } +} + + +///////////// factory实现的单例 ///////////// +class Singleton { + factory Singleton() => const Singleton._internal_(); + const Singleton._internal_(); +} + + +///////////// 实际开发可能这么使用 ///////////////////////// + +abstract class Animal { + factory Animal(String type) { + switch (type) { + case "cat": + return new Cat(); + case "dog": + return new Dog(); + default: + throw Exception("输入的类型: '$type' 不是动物"); + } + } +} + +class Cat implements Animal { + Cat() { + print('猫'); + } +} + +class Dog implements Animal { + Dog() { + print('狗'); + } +} diff --git a/projects/dart_demo/test/8-class/3-functions/3-init_list/1-init_list_demo1.dart b/projects/dart_demo/test/8-class/3-functions/3-init_list/1-init_list_demo1.dart new file mode 100644 index 0000000..7a83457 --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/3-init_list/1-init_list_demo1.dart @@ -0,0 +1,32 @@ +void main() { + new Test1(4, 3); + Map json = { + 'a': 1, + 'b': 5, + 'c': 12, + }; + + new Test2.from(json); +} + + +// 有参构造初始化 +class Test1 { + var x, y; + Test1(var x, var y) + : x = x, + y = y { + print('Test1 有参构造初始化'); + } +} + +// 命名构造的初始化 +class Test2 { + var x, y; + + Test2.from(Map json) + : x = json['x'], + y = json['y'] { + print('Test2.from(): ($x, $y)'); + } +} \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/3-functions/3-init_list/2-init_list_demo2.dart b/projects/dart_demo/test/8-class/3-functions/3-init_list/2-init_list_demo2.dart new file mode 100644 index 0000000..2394809 --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/3-init_list/2-init_list_demo2.dart @@ -0,0 +1,25 @@ +// 使用assert在初始化列表用来校验输入参数 +void main() { + new Test1(4, 3); + + new Test2.withAssert(5, 10); +} + +// 有参构造使用assert校验参数: + +class Test1 { + var x, y; + + Test1(var x, var y) : assert(x >= 0) { + print('Test5(): ($x, $y)'); + } +} + +// 命名构造使用assert校验参数: + +class Test2 { + var x, y; + Test2.withAssert(this.x, this.y) : assert(x >= 0) { + print('Test2.withAssert(): ($x, $y)'); + } +} diff --git a/projects/dart_demo/test/8-class/3-functions/3-init_list/3-init_list_demo3.dart b/projects/dart_demo/test/8-class/3-functions/3-init_list/3-init_list_demo3.dart new file mode 100644 index 0000000..f3c2756 --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/3-init_list/3-init_list_demo3.dart @@ -0,0 +1,23 @@ +// 如果没有更多实际操作内容,可以简写。 +void main() { + new Test1(4, 3); + + new Test2.withAssert(5, 10); +} + +// 有参构造使用assert校验参数: + +class Test1 { + var x, y; + + //如果没有更多实际操作内容 可以这样简写: + Test1(var x, var y) : assert(x >= 0); + +} + +// 命名构造使用assert校验参数: + +class Test2 { + var x, y; + Test2.withAssert(this.x, this.y) : assert(x >= 0); +} \ No newline at end of file diff --git a/projects/dart_demo/test/8-class/3-functions/3-init_list/4-init_list_demo4.dart b/projects/dart_demo/test/8-class/3-functions/3-init_list/4-init_list_demo4.dart new file mode 100644 index 0000000..fe26b0a --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/3-init_list/4-init_list_demo4.dart @@ -0,0 +1,13 @@ +// 把构造的初始化和assert校验同时使用 +void main() { + new Test1(5, 10); +} + +class Test1 { + var x, y; + Test1(var x, var y) : assert(x > 0) { + this.x = x; + this.y = y; + print('Test1 有参构造初始化'); + } +} diff --git a/projects/dart_demo/test/8-class/3-functions/3-init_list/5-init_list_demo5.dart b/projects/dart_demo/test/8-class/3-functions/3-init_list/5-init_list_demo5.dart new file mode 100644 index 0000000..b7b8a51 --- /dev/null +++ b/projects/dart_demo/test/8-class/3-functions/3-init_list/5-init_list_demo5.dart @@ -0,0 +1,19 @@ +import 'dart:math'; + +// 设置final字段,初始化程序时更方便 + +void main() { + var p = new Test1(4, 3); + print('长方形的对角线长度:${p.hypotenuse}'); +} + +class Test1 { + final num width; + final num height; + final num hypotenuse; + + Test1(width, height) + : width = width, + height = height, + hypotenuse = sqrt(width * width + height * height); +} diff --git a/projects/dart_demo/test/9-library/libs/mylib.dart b/projects/dart_demo/test/9-library/libs/mylib.dart new file mode 100644 index 0000000..30d812e --- /dev/null +++ b/projects/dart_demo/test/9-library/libs/mylib.dart @@ -0,0 +1,17 @@ +// 这是一个库 命名为mylib +library mylib; + +// 希望使用mylib的时候 自动使用otherlib.dart 可以使用export关键字引入其他库 +export 'otherlib.dart'; +// 导入otherlib2.dart +export 'otherlib2.dart'; + +class MyLib { + void test() { + print('mylib.dart: MyLib : test()函数'); + } +} + +void test2() { + print('mylib.dart: test2()函数'); +} diff --git a/projects/dart_demo/test/9-library/libs/otherlib.dart b/projects/dart_demo/test/9-library/libs/otherlib.dart new file mode 100644 index 0000000..c99f979 --- /dev/null +++ b/projects/dart_demo/test/9-library/libs/otherlib.dart @@ -0,0 +1,8 @@ +// 其它的库 +library otherlib; + +class otherLib {} + +void test() { + print('otherLib库 : test()函数'); +} diff --git a/projects/dart_demo/test/9-library/libs/otherlib2.dart b/projects/dart_demo/test/9-library/libs/otherlib2.dart new file mode 100644 index 0000000..8a0197f --- /dev/null +++ b/projects/dart_demo/test/9-library/libs/otherlib2.dart @@ -0,0 +1,8 @@ +// 其它的库 +library otherlib2; + +class otherLib2 {} + +void test2() { + print('otherLib2库 : test2()函数'); +} diff --git a/projects/dart_demo/test/9-library/libs/testlib1.dart b/projects/dart_demo/test/9-library/libs/testlib1.dart new file mode 100644 index 0000000..3e458e4 --- /dev/null +++ b/projects/dart_demo/test/9-library/libs/testlib1.dart @@ -0,0 +1,18 @@ +// 关于part 和 part of +// 1. 不能同时使用library和part of,它们用于指定属于库的内容。 +// 1. B库是A库的一部分表示:part of A库名称 +// 2. 如果B库声明A库的一部分,同时A库也想声明它的一部分是B库,正确写法: +// 必须是A库写了part 'B库的路径' 同时B库声明part of A库名称。 +// 这种情况下,某一边没有声明的话,就会报错。 + + +// 第1个库: +library testlib1; + +// 可以不写 +part 'testlib2.dart'; + + +void run() { + print('testlib1库 : run()函数'); +} diff --git a/projects/dart_demo/test/9-library/libs/testlib2.dart b/projects/dart_demo/test/9-library/libs/testlib2.dart new file mode 100644 index 0000000..08a930c --- /dev/null +++ b/projects/dart_demo/test/9-library/libs/testlib2.dart @@ -0,0 +1,15 @@ +// 第2个库 +// 不能同时声明library 和 part of 冲突了。 +// library testlib2; + +// part of 表示这个库是testlib库的一部分 +part of testlib1; + + +class testLib2 { + +} + +void start() { + print('testlib2库 : start()函数'); +} diff --git a/projects/dart_demo/test/9-library/test1.dart b/projects/dart_demo/test/9-library/test1.dart new file mode 100644 index 0000000..6b5ccb1 --- /dev/null +++ b/projects/dart_demo/test/9-library/test1.dart @@ -0,0 +1,42 @@ +// 普通导入库 +// import 'libs/mylib.dart'; + +///////////////////////////////////////// + +// test2.dart 和 test3.dart都有相同的hello()函数,这样写会报错 +// import 'test2.dart'; +// import 'test3.dart'; +// 解决方案:给导入的库指定一个前缀 方便识别 +// import 'test2.dart'; +// import 'test3.dart' as test3; + +///////////////////////////////////////// + +// 仅导入mylib.dart里面的test2函数 +// import 'libs/mylib.dart' show test2; + +// 刚好和show相反 除了test2函数之外 其它的都导入 +// import 'libs/mylib.dart' hide test2; +//我们想导入mylib库,但是不想用里面的otherLib这个库 可以这样写 +// import 'libs/mylib.dart' hide otherLib; + +///////////////////////////////////////// + +// 延迟导入的前缀 +// 当我们import一个库的时候,如果使用了as 不能同时使用deferred as +import 'libs/mylib.dart' deferred as tests; +import 'dart:async'; + +void main() { + // hello(); + // test3.hello(); + + hello(); + +} + +// 延迟导入的函数 需要使用loadLibrary +Future hello() async { + await tests.loadLibrary(); + tests.test2(); +} diff --git a/projects/dart_demo/test/9-library/test2.dart b/projects/dart_demo/test/9-library/test2.dart new file mode 100644 index 0000000..23bc3f5 --- /dev/null +++ b/projects/dart_demo/test/9-library/test2.dart @@ -0,0 +1,3 @@ +void hello() { + print('test2.dart : hello()函数'); +} diff --git a/projects/dart_demo/test/9-library/test3.dart b/projects/dart_demo/test/9-library/test3.dart new file mode 100644 index 0000000..8a2160e --- /dev/null +++ b/projects/dart_demo/test/9-library/test3.dart @@ -0,0 +1,3 @@ +void hello(){ + print('test3.dart : hello()函数'); +} \ No newline at end of file diff --git a/projects/dart_demo/test/functions.dart b/projects/dart_demo/test/functions.dart deleted file mode 100644 index a06e296..0000000 --- a/projects/dart_demo/test/functions.dart +++ /dev/null @@ -1,60 +0,0 @@ -void main() { - /// 调用可选的命名参数 - enableFlags(bold: true, hidden: false); - - /// 调用可选的位置参数 - say('Bob', 'Howdy'); //结果是: Bob says Howdy - /// 用第三个参数调用这个函数的例子: - say('Bob', 'Howdy', 'smoke signal'); //结果是:Bob says Howdy with a smoke signal - - /// 调用为命名参数设置默认值 调用的时候:bold will be true; hidden will be false. - enableFlags2(bold: true); - - /// 调用为位置参数设置默认值 - say2('Bob', 'Howdy'); //结果是:Bob says Howdy with a carrier pigeon -} - -/// 可选的命名参数 -//设置[bold]和[hidden]标志 -void enableFlags({bool bold, bool hidden}) { - // ... -} - -/// 可选的位置参数 -String say(String from, String msg, [String device]) { - var result = '$from says $msg'; - if (device != null) { - result = '$result with a $device'; - } - return result; -} - -/// 如何为命名参数设置默认值 -void enableFlags2({bool bold = false, bool hidden = false}) { - // ... -} - -/// 如何为位置参数设置默认值 -String say2(String from, String msg, - [String device = 'carrier pigeon', String mood]) { - var result = '$from says $msg'; - if (device != null) { - result = '$result with a $device'; - } - if (mood != null) { - result = '$result (in a $mood mood)'; - } - return result; -} - -/// 使用list 或者map设置默认值 -void doStuff( - {List list = const [1, 2, 3], - Map gifts = const { - 'first': 'paper', - 'second': 'cotton', - 'third': 'leather' - }}) { - print('list: $list'); - print('gifts: $gifts'); -} diff --git a/projects/dart_demo/test/operators.dart b/projects/dart_demo/test/operators.dart deleted file mode 100644 index 55f7a7d..0000000 --- a/projects/dart_demo/test/operators.dart +++ /dev/null @@ -1,226 +0,0 @@ -/// 运算符的使用 -void main() { - suanshu(); - fuzhi(); - guanxi(); - luoji(); - wei(); - weiyi(); - sanyuan(); - qita(); -} - -/// 算数运算符 -void suanshu() { - print('\n=============='); - - print(13 + 3); //16 - print(13 - 3); //10 - print(13 * 3); //39 - - print('=============='); - - print(13 / 3); //4.333333333333333 - print(13 / -3); //-4.333333333333333 - print(-13 / 3); //-4.333333333333333 - print(-13 / -3); //4.333333333333333 - - print('=============='); - - print(13 ~/ 3); //4 - print(13 ~/ -3); //-4 - print(-13 ~/ 3); //-4 - print(-13 ~/ -3); //4 - - print('=============='); - - print(13 % 3); //1 - print(13 % -3); //1 - print(-13 % 3); //2 - print(-13 % -3); //2 - - print('=============='); - - print(-1); //-1 “-”表示负数的符号 - - print('=============='); - - // i++ :先引用后增加,i--同理 - // ++i :先增加后引用,--i同理 - - int i = 1; - int x = 1; - x = i++; //先让x变成i的值1,再让i加1 - print(x); //输出的x为1 - print(i); //输出的i为2 - - print('=============='); - - int a = 1; - int b = 1; - b = ++a; //先让a加1, 再让b变成a的值2 - print(a); //输出的b为2 - print(b); //输出的a为2 -} - -/// 赋值运算符 -void fuzhi() { - print('\n=================='); - - print('a初始值全部为2.0'); - double a1 = 2.0; - a1 += 2; - print("a1+= 2 结果是 $a1"); //4.0 - - double a2 = 2.0; - a2 -= 2; - print("a2-= 2 结果是 $a2"); //0.0 - - double a3 = 2.0; - a3 *= 2; - print("a3*=2 结果是 $a3"); //4.0 - - double a4 = 2.0; - a4 %= 2; - print("a4%=2 结果是 $a4"); //0.0 - - double a5 = 2.0; - a5 = a5 / 2; - print("a5/=2 结果是 $a5"); //1.0 - - print('b初始值全部为16'); - - int b1 = 16; - b1 ~/= 2; - print("b1~/=2 结果是 $b1"); //8 - - int b2 = 16; - b2 &= 2; - print("b2&=2 结果是 $b2"); //0 - - int b3 = 16; - b3 |= 2; - print("b3|=2 结果是 $b3"); //18 - - int b4 = 16; - b4 ^= 2; - print("b4~=2 结果是 $b4"); //18 - - int b5 = 16; - b5 >>= 2; - print("b5>>=2 结果是: $b5"); //4 - - int b6 = 16; - b6 <<= 2; - print("b6<<=2 结果是: $b6"); //64 - - print('=================='); - - /// /=不能用在int值上面,因为int除以一个数结果是double值 - /// ~/= &= |= ^= 2 >>= 2 <<= 2这些不能用在double值上面,因为结果是int值 -} - -/// 关系运算符 -void guanxi() { - print('\n=================='); - - int a = 1; - - print(a == 1); // true - print(a != 1); // false - print(a > 1); // false - print(a < 1); // false - print(a >= 1); // true - print(a <= 1); // true - - print('=================='); -} - -/// 逻辑运算符 -void luoji() { - print('\n=================='); - - // !expr 反转表达式(将false更改为true,反之亦然) - // || 逻辑双或 - // && - // | 没有 逻辑或 - // & 没有 逻辑与 - bool done = true; - int col = 1; - if (done && (col == 0 || col == 3)) { - // ...Do something... - print('OK'); - } else { - print('不满足条件'); - } - - print('=================='); -} - -/// 位运算符 -void wei() { -// & 位与 有0则0 -// | 位或 有1则1 -// ^ 位异或 相同为0,不同为1 -// ~expr 按位取反(包括符号位) - - print('\n=================='); - - final value = 4; - final bitmask = 2; - - // 4 二进制是 100 2 二进制是 10 ~2 二进制是101 - - // 4 & 2 就是 - // 100 - // & 010 - //结果:000 - - // 4 & ~2 就是 - // 100 - // & 101 - //结果:100 - - // 4 | 2 就是 - // 100 - // | 010 - //结果:110 - - // 4 ^ 2 就是 - // 100 - // ^ 010 - //结果:110 - - print((value & bitmask)); //0 &是有0则0,结果是000,换算成10进制是0 - print((value & ~bitmask)); // 4 结果是100,换算成10进制是4 - print((value | bitmask)); // 6 结果是110,换算成10进制是6 - print((value ^ bitmask)); // 6 结果是110,换算成10进制是6 - - print('=================='); -} - -/// 位移运算符 -void weiyi() { - // << 向左移动 左边最高位丢弃,左边补齐0 - // >> 向右移动 最高位是0,左边补齐0;最高位是1,左边补齐1 - - print('\n=================='); - - int value = 4; - print(value << 2); // 16 相当于 4 *(2的平方) - print(value >> 2); // 1 相当于 4 /(2的平方) - - print('=================='); -} - -/// 三元运算符 -void sanyuan() { - bool isPublic; - String visibility = isPublic ? 'public' : 'private'; - - String playerName(String name) => name ?? 'Guest'; - //相当于 String playerName(String name) => name != null ? name : 'Guest'; -} - -/// 其他运算符 -void qita() {} diff --git a/projects/flutter-demo/.idea/codeStyles/Project.xml b/projects/flutter-demo/.idea/codeStyles/Project.xml new file mode 100644 index 0000000..30aa626 --- /dev/null +++ b/projects/flutter-demo/.idea/codeStyles/Project.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/projects/flutter-demo/.idea/inspectionProfiles/Project_Default.xml b/projects/flutter-demo/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000..6560a98 --- /dev/null +++ b/projects/flutter-demo/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,36 @@ + + + + \ No newline at end of file diff --git a/projects/flutter-demo/.idea/libraries/Dart_Packages.xml b/projects/flutter-demo/.idea/libraries/Dart_Packages.xml new file mode 100644 index 0000000..a84d3dc --- /dev/null +++ b/projects/flutter-demo/.idea/libraries/Dart_Packages.xml @@ -0,0 +1,340 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/projects/flutter-demo/.idea/libraries/Dart_SDK.xml b/projects/flutter-demo/.idea/libraries/Dart_SDK.xml new file mode 100644 index 0000000..5cb8b95 --- /dev/null +++ b/projects/flutter-demo/.idea/libraries/Dart_SDK.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/projects/flutter-demo/.idea/libraries/Flutter_Plugins.xml b/projects/flutter-demo/.idea/libraries/Flutter_Plugins.xml new file mode 100644 index 0000000..6f660d6 --- /dev/null +++ b/projects/flutter-demo/.idea/libraries/Flutter_Plugins.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/projects/flutter-demo/.idea/markdown-navigator.xml b/projects/flutter-demo/.idea/markdown-navigator.xml new file mode 100644 index 0000000..7753d6d --- /dev/null +++ b/projects/flutter-demo/.idea/markdown-navigator.xml @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/projects/flutter-demo/.idea/markdown-navigator/profiles_settings.xml b/projects/flutter-demo/.idea/markdown-navigator/profiles_settings.xml new file mode 100644 index 0000000..57927c5 --- /dev/null +++ b/projects/flutter-demo/.idea/markdown-navigator/profiles_settings.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/projects/flutter-demo/.idea/misc.xml b/projects/flutter-demo/.idea/misc.xml new file mode 100644 index 0000000..17d4cf5 --- /dev/null +++ b/projects/flutter-demo/.idea/misc.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/projects/flutter-demo/.idea/modules.xml b/projects/flutter-demo/.idea/modules.xml new file mode 100644 index 0000000..09b142c --- /dev/null +++ b/projects/flutter-demo/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/projects/flutter-demo/.idea/workspace.xml b/projects/flutter-demo/.idea/workspace.xml new file mode 100644 index 0000000..e01f8ce --- /dev/null +++ b/projects/flutter-demo/.idea/workspace.xml @@ -0,0 +1,494 @@ + + + + + + + + + + + + + Log + log + new Log + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +