flutter學習筆記

重要函數:

1.runApp函數接受一個給定的Widget並使其成爲widget樹的根html

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

2.android

無狀態的widget: StatelessWidgetgit

有狀態的widget: StatefulWidgetredux

3.buildapi

widge的主要工做是實現一個build函數,用以構建自身緩存

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Startup Name Generator',
      theme: new ThemeData(
        primaryColor: Colors.white
      ),
      home: new RandomWords(),
    );
  }
}

4.Material組件aterial應用程序以Material widget開始性能優化

Navigator管理由字符串標識的Widge棧(頁面路由棧)app

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Startup Name Generator',
      theme: new ThemeData(
        primaryColor: Colors.white
      ),
      home: new RandomWords(),
    );
  }
}

5.GestureDetector監聽手勢框架

 

6.位置相似於flex佈局less

crossAaisAlignment:子元素放置位置(十字軸)

mainAxisAlignment:子元素放置位置(主軸)

mainAxisSize:主軸佔用多少空間

1.在Dart語言中使用下劃線前綴表四符,會強制其變成私有的

2.i ~/ 2表示i除以2,但返回值是整型(向下取整)

 

經常使用類 

1.Expanded:用於展開RowColumnFlex的子項的窗口小部件

 

2.Scaffold:

appBar:水平欄,在程序的頂部

BottomAppBar:水平條,一般位於程序底部

 

3.appBar

actions:要在標題小部件後顯示的小部件

 

4.Flutter之Offstage組件

/

**

* 控制child是否顯示

*

當offstage爲true,控件隱藏; 當offstage爲false,顯示;

當Offstage不可見的時候,若是child有動畫等,須要手動停掉,Offstage並不會停掉動畫等操做。

 

const Offstage({ Key key, this.offstage = true, Widget child })

*/

 

5.導航/路由
  Navigator.of(context).push(new MaterialPageRoute(builder: (context)      {
      //指定跳轉的頁面
      return new Demo1();
    },));

6.經常使用元素
(1)Wrap首先來看Wrap,Wrap是一個可使子控件自動換行的控件,默認的方向是水平的
Wrap({
    Key key,
    this.direction = Axis.horizontal,   //排列方向,默認水平方向排列
    this.alignment = WrapAlignment.start,  //子控件在主軸上的對齊方式
    this.spacing = 0.0,  //主軸上子控件中間的間距
    this.runAlignment = WrapAlignment.start,  //子控件在交叉軸上的對齊方式
    this.runSpacing = 0.0,  //交叉軸上子控件之間的間距
    this.crossAxisAlignment = WrapCrossAlignment.start,   //交叉軸上子控件的對齊方式
    this.textDirection,   //textDirection水平方向上子控件的起始位置
    this.verticalDirection = VerticalDirection.down,  //垂直方向上子控件的其實位置
    List<Widget> children = const <Widget>[],   //要顯示的子控件集合
  })

 

(2)SafeArea異形屏適配利器
 SafeArea(
      child: Align(
        alignment: Alignment(-1, -1),
        child: Container(
          child: Text(
            "Hello",
          ),
        ),
      ),
  );


7.文字超出省略號
 child: new Text(
        'Hello, How are you?Hello, How are you?Hello, How are you?Hello, How are you?',
        textAlign: TextAlign.center,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(fontWeight: FontWeight.bold,fontSize: 48.0),
        maxLines: 2,
      ),

8.flutter 版本
git checckout v0.8.1  切換到某個版本
flutter upgrade  //同時更新Flutter SDK和你的依賴包

 

9.設置appBar的高度

 

使用腳手架Scaffold能夠設置AppBar,想要設置高度,在AppBar外包一層PreferredSize,設置preferredSize的屬性爲想要的高度便可

   Scaffold( 
        appBar: PreferredSize(
        child: AppBar(
        ),
        preferredSize: Size.fromHeight(screenSize.height * 0.07))
);

10.獲取widget的寬高
final size =MediaQuery.of(context).size;
final width =size.width;
final height =size.height; 

注意:

MediaQuery.of(context) 要在WidgetsApp or MaterialApp 中,否則會報錯


(在使用 MediaQuery.of(context)的地方並無一個 WidgetsApp or MaterialApp 來提供數據)

例:

import 'package:flutter/material.dart';


class GetWidgetWidthAndHeiget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}


class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    final width = size.width;
    final height = size.height;
    print('width is $width; height is $height');
    return Scaffold(
      appBar: AppBar(
        title: Text('Width & Height'),
      ),
      body: Center(
        child: Container(
          color: Colors.redAccent,
          width: width / 2,
          height: height / 2,
        ),
      ),
    );
  }
}
11.手勢控制GestureDetector
import 'package:flutter/material.dart';


void main() {
  runApp(new MaterialApp(
    title: "個人應用",
    home: new MyButton(),
  ));
}


class MyButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    //GestureDetector並不具備顯示效果,而是檢測由用戶作出的手勢(點擊拖動和縮放)
    return new GestureDetector(
      //發生點擊事件後回調
      onTap: () {
        print("hia");
      },
      //發生雙擊時間後回調
      onDoubleTap: (){
        print("hia hia");
      },
     // 長按事件
      onLongPress: (){
        print("hia hia hia........");
      },
      child: new Container(
        height: 36.0,
        padding: const EdgeInsets.all(8.0),
        //上下左右都偏移8像素邊距
        margin: const EdgeInsets.symmetric(horizontal: 8.0),
        //symmetric的參數是可選的 水平方向
        // 背景裝飾
        decoration: new BoxDecoration(
          //圓角和顏色
            borderRadius: new BorderRadius.circular(5.0),
            color: Colors.lightGreen[500]),
        child: new Center(child: new Text("點擊監聽")),
      ),
    );
  }

 

 

 

Flutter 顏色的表示方式
Color c = const Color(0xFF0099ff);//0x 後面開始 兩位FF表示透明度16進制,
Color c = const Colors.red[100];
Color c = const Color.fromARGB(0xFF, 0x42, 0xA5, 0xF5);
Color c = const Color.fromARGB(255, 66, 165, 245);
Color c = const Color.fromRGBO(66, 165, 245, 1.0);//opacity:不透明度


 

TextField
const TextField({
    Key key,
    this.controller,            //控制器,控制TextField文字
    this.focusNode,
    this.decoration: const InputDecoration(),      //輸入器裝飾
    TextInputType keyboardType: TextInputType.text, //輸入的類型
    this.style,
    this.textAlign: TextAlign.start, //文本對齊方式
    this.autofocus: false,    //是否自動對焦
    this.obscureText: false,  //是否隱藏輸入
    this.autocorrect: true,   //是否自動更正
    this.maxLines: 1,         //最大行數
    this.maxLength,           //最大長度
    this.maxLengthEnforced: true,
    this.onChanged,            //文字改變觸發
    this.onSubmitted,          //文字提交觸發(鍵盤按鍵)
    this.onEditingComplete,  //當用戶提交可編輯內容時調用
    this.inputFormatters,
    this.enabled,           //是否禁用
    
    this.cursorWidth = 2.0,//光標的樣式
    this.cursorRadius,     //光標的樣式
    this.cursorColor,      //光標的樣式
    this.keyboardAppearance,
  })

 

Slider

Slider 各部分的術語是:

  • thumb - 用戶拖動時水平滑動的形狀。
  • track - 滑塊拇指滑過的線。
  • value - 當用戶拖動拇指指示所選值時彈出的形狀。
  • active - 滑塊的「活動」一側是拇指和最小值之間的一側。
  • inactive - 滑塊的「非活動」側是拇指和最大值之間的一側。

Slider 有如下經常使用屬性:

  • activeColor → Color - 激活時的顏色。
  • divisions → int - 離散部分的數量。
  • inactiveColor → Color - 滑塊軌道的非活動部分的顏色。
  • label → String 滑塊處於活動狀態時顯示在滑塊上方的標籤。
  • max → double - 用戶能夠選擇的最大值。
  • min → double - 用戶能夠選擇的最小值。
  • onChanged → ValueChanged - 改變時觸發。
  • onChangeEnd → ValueChanged - 改變後觸發。
  • onChangeStart → ValueChanged - 改變前觸發。
  • value → double - 滑塊的值。
Switch
Switch 有如下經常使用屬性:
activeColor → Color - 激活時原點的顏色。
activeThumbImage → ImageProvider - 原點還支持圖片,激活時的效果。
activeTrackColor → Color - 激活時橫條的顏色。
inactiveThumbColor → Color - 非激活時原點的顏色。
inactiveThumbImage → ImageProvider - 非激活原點的圖片效果。
inactiveTrackColor → Color - 非激活時橫條的顏色。
onChanged → ValueChanged - 改變時觸發。
value → bool - 切換按鈕的值。

 

SwitchListTile
value: 是否選中 是否打開
onChanged: 當打開關閉的時候的回調
activeColor: 選中時 滑塊的顏色
activeTrackColor: 選中時 滑道的顏色
inactiveThumbColor: 未選中時 滑塊的顏色
inactiveTrackColor: 未選中時 滑道的顏色
activeThumbImage: 選中時 滑塊的圖片
inactiveThumbImage: 未選中時 滑塊的圖片
title: 標題 典型的是 Text
subtitle: 副標題 在標題下面的 典型的是 Text
isThreeLine = false: 是否是三行, true 時: subtitle 不能爲null, false時能夠爲 null
dense: 是否垂直密集居中
secondary: 左邊的一個東西
selected = false: 若是爲 true ,則 text 和 icon 都用 activeColor 時的color

 

Text
textAlign: TextAlign.center, //文本對齊方式  居中
textDirection: TextDirection.ltr, //文本方向
softWrap: false, //是否自動換行 false文字不考慮容器大小  單行顯示   超出;屏幕部分將默認截斷處理
overflow: TextOverflow
  .ellipsis, //文字超出屏幕以後的處理方式  TextOverflow.clip剪裁   TextOverflow.fade 漸隱  TextOverflow.ellipsis省略號
textScaleFactor: 2.0, //字體顯示的賠率
maxLines: 10, //最大行數
style: new TextStyle(
decorationColor: const Color(0xffffffff), //線的顏色
decoration: TextDecoration
    .none, //none無文字裝飾   lineThrough刪除線   overline文字上面顯示線    underline文字下面顯示線
decorationStyle: TextDecorationStyle
    .solid, //文字裝飾的風格  dashed,dotted虛線(簡短間隔大小區分)  double三條線  solid兩條線
wordSpacing: 0.0, //單詞間隙(負值可讓單詞更緊湊)
letterSpacing: 0.0, //字母間隙(負值可讓字母更緊湊)
fontStyle: FontStyle.italic, //文字樣式,斜體和正常
fontSize: 20.0, //字體大小
fontWeight: FontWeight.w900, //字體粗細  粗體和正常
color: const Color(0xffffffff), //文字顏色

 

Button

RaisedButton :凸起的按鈕,其實就是Android中的Material Design風格的Button ,繼承自MaterialButton

FlatButton :扁平化的按鈕,繼承自MaterialButton

OutlineButton :帶邊框的按鈕,繼承自MaterialButton

IconButton :圖標按鈕,繼承自StatelessWidget

 

RaisedButton({
    Key key,
  //點擊按鈕的回調出發事件
    @required VoidCallback onPressed,
  //水波紋高亮變化回調
    ValueChanged<bool> onHighlightChanged,
  //按鈕的樣式(文字顏色、按鈕的最小大小,內邊距以及shape)[ Used with [ButtonTheme] and [ButtonThemeData] to define a button's base
//colors, and the defaults for the button's minimum size, internal padding,and shape.]
    ButtonTextTheme textTheme,
    //文字顏色
    Color textColor,
    //按鈕被禁用時的文字顏色
    Color disabledTextColor,
    //按鈕的顏色
    Color color,
    //按鈕被禁用時的顏色  
    Color disabledColor,
    //按鈕的水波紋亮起的顏色
    Color highlightColor,
    //水波紋的顏色
    Color splashColor,
    //按鈕主題高亮
    Brightness colorBrightness,
    //按鈕下面的陰影長度
    double elevation,
    //按鈕高亮時的下面的陰影長度
    double highlightElevation,
    double disabledElevation,
    EdgeInsetsGeometry padding,
    ShapeBorder shape,
    Clip clipBehavior = Clip.none,
    MaterialTapTargetSize materialTapTargetSize,
    Duration animationDuration,
    Widget child,
  }

 

FloatingActionButton({
    Key key,
    //  按鈕上的組件,能夠是Text、icon, etc.
    this.child,
    //長按提示
    this.tooltip,
    // child的顏色(盡在child沒有設置顏色時生效)
    this.foregroundColor,
    //背景色,也就是懸浮按鍵的顏色
    this.backgroundColor,
    this.heroTag = const _DefaultHeroTag(),
    //陰影長度
    this.elevation = 6.0,
    //高亮時陰影長度
    this.highlightElevation = 12.0,
    //按下事件回調
    @required this.onPressed,
    //是小圖標仍是大圖標
    this.mini = false,
    //按鈕的形狀(例如:矩形Border,圓形圖標CircleBorder)
    this.shape = const CircleBorder(),
    this.clipBehavior = Clip.none,
    this.materialTapTargetSize,
    this.isExtended = false,
  })


 

PopupMenuButton({
    Key key,
//構建彈出式列表數據
    PopupMenuItemBuilder<T> @required this.itemBuilder,
//初始值
   T initialValue,
//選中時的回調
 PopupMenuItemSelected<T> onSelected;,
//當未選中任何條目後彈窗消失時的回調
     final PopupMenuCanceled onCanceled;,
//
    this.tooltip,
//彈窗陰影高度
    this.elevation = 8.0,
//邊距
    this.padding = const EdgeInsets.all(8.0),
//彈窗的位置顯示的組件,默認爲三個點...
    this.child,
//跟child效果一致
    this.icon,
//彈窗偏移位置
    this.offset = Offset.zero,
  })

 

Chip
Chip({
    Key key,
    this.avatar,//標籤左側Widget,通常爲小圖標
    @required this.label,//標籤
    this.labelStyle,
    this.labelPadding,//padding
    this.deleteIcon//刪除圖標,
    this.onDeleted//刪除回調,爲空時不顯示刪除圖標,
    this.deleteIconColor//刪除圖標的顏色,
    this.deleteButtonTooltipMessage//刪除按鈕的tip文字,
    this.shape//形狀,
    this.clipBehavior = Clip.none,
    this.backgroundColor//背景顏色,
    this.padding,
    this.materialTapTargetSize//刪除圖標material點擊區域大小,
  })

 

ScrollView
cacheExtent → double - 視口在可見區域以前和以後有一個區域,用於緩存用戶滾動時即將可見的項目。
controller → ScrollController - 一個可用於控制滾動視圖滾動到的位置的對象。
physics → ScrollPhysics - 滾動視圖應如何響應用戶輸入。
primary → bool - 是不是與父級關聯的主滾動視圖。
reverse → bool - 滾動視圖是否在閱讀方向上滾動。
scrollDirection → Axis - 滾動視圖滾動的軸。
shrinkWrap → bool - 應該根據正在查看的內容肯定滾動視圖的範圍。

 

其餘知識:

EdgeInsets 這個類 經過他能夠很好的控制widget上下左右的偏移量 有.all所有設置 也有.symmetric水平和垂直可選  也有.only上下左右可選

EdgeInsets.fromLTRB(10,10,10,10) ,L表示左邊距(left縮寫),T表示上邊距(top縮寫),R表示右邊距(right縮寫),B表示底邊距(bottom縮寫),四個值能夠分開寫;

 

12. fish_redux
view :

它主要包含三方面的信息:

  • 視圖是徹底由數據驅動。
  • 視圖產生的事件、回調,經過 Dispatch 發出「意圖」,不作具體的實現。
  • 須要用到的組件依賴等,經過 ViewService 標準化調用。 好比一個典型的符合 View 簽名的函數。
effect:

Effect 是對非修改數據行爲的標準定義,它是一個函數簽名: (Context, Action) => Object,它主要包含四方面的信息:

  • 接收來自 View 的「意圖」,也包括對應的生命週期的回調,而後作出具體的執行。
  • 它的處理多是一個異步函數,數據可能在過程當中被修改,因此咱們不崇尚持有數據,而經過上下文來獲取最新數據。
  • 它不修改數據, 若是修要,應該發一個 Action 到 Reducer 裏去處理。
  • 它的返回值僅限於 bool or Future, 對應支持同步函數和協程的處理流程。 好比:良好的協程的支持。

 

Reducer

它主要包含三方面的信息

  • 接收一個「意圖」, 作出數據修改。
  • 若是要修改數據,須要建立一份新的拷貝,修改在拷貝上。
  • 若是數據修改了,它會自動觸發 State 的層層數據的拷貝,再以扁平化方式通知組件刷新。

 

Adapter:

Adapter 也是對局部的展現和功能的封裝。它爲 ListView 高性能場景而生,它是 Component 實現上的一種變化。

1.它的目標是解決 Component 模型在 flutter-ListView 的場景下的 3 個問題:

  • 將一個"Big-Cell"放在 Component 裏,沒法享受 ListView 代碼的性能優化。
  • Component 沒法區分 appear|disappear 和 init|dispose 。
  • Effect 的生命週期和 View 的耦合,在 ListView 的場景下不符合直觀的預期。 歸納的講,咱們想要一個邏輯上的 ScrollView,性能上的 ListView ,這樣的一種局部展現和功能封裝的抽象。 作出這樣獨立一層的抽象是, 咱們看實際的效果, 咱們對頁面不使用框架,使用框架 Component,使用框架 Component+Adapter 的性能基線對比。

2.Reducer is long-lived, Effect is medium-lived, View is short-lived. 咱們經過不斷的測試作對比,以某 android 機爲例。

3.使用框架前 咱們的詳情頁面的 FPS,基線在 52FPS。

4.使用框架, 僅使用 Component 抽象下,FPS 降低到 40, 遭遇「Big-Cell」的陷阱。

5.使用框架,同時使用 Adapter 抽象後,FPS 提高到 53,回到基線以上,有小幅度的提高。

 

static Action didLoadAction(Home home) {
  return Action(HomePageAction.didLoad, payload: home);
}
  


void _init(Action action, Context<HomePageState> ctx) async {
  APIs.getHome().then((home) {
    ctx.dispatch(HomePageActionCreator.didLoadAction(home));
  });
}


onSelect(Action action, Context ctx) async {
  String videoId = action.payload["videoId"];
  VideoDetail videoDetail = await APIs.getVideo(videoId);
  Map<String, dynamic> payload = {
    "videoId": videoId,
    "videoDetail": videoDetail
  };
  Navigator.of(ctx.context).push(MaterialPageRoute(builder: (context) {
    return VideoPage().buildPage(payload);
  }));
}

 

13.顏色透明度

帶有accent的顏色每一個有4中顏色,如


Colors.redAccent,Colors.redAccent[100], Colors.redAccent[200], Colors.redAccent[400], Colors.redAccent[700], 


Color.fromARGB(100, 10, 100, 100),A表示不透明度,值從0-255,RGB值也是從0-255;
Color.fromRGBO(100, 10, 10, 1),O表示不透明度,值從0-1,RGB值是從0-255;
Color.alphaBlend(Color.fromRGBO(10, 10, 255, 0.1), Color.fromRGBO(100, 10, 255, 0.5)) ,這個是顏色的混合,
顏色會根據不透明度進行合併;
若是前者的不透明度爲1,就只顯示前者顏色,前者爲0,顏色爲後者,不然就是按照先後者的不透明度和顏色進行混合

 

 

 

tools:replace="android:label"
xmlns:tools="http://schemas.android.com/tools"
tools:replace="android:label,android:allowBackup"
buildToolsVersion '28.0.2'
tools:replace="android:label,android:allowBackup,android:appComponentFactory"
xmlns:tools="http://schemas.android.com/tools"


implementation 'androidx.appcompat:appcompat:1.0.0-alpha1'
implementation 'androidx.constraintlayout:constraintlayout:1.1.2'

 

 

13.生命週期

(1)initState

當插入渲染樹的時候調用,這個函數在生命週期中只調用一次。這裏能夠作一些初始化工做,好比初始化State的變量。

 

(2)didChangeDependencies

使用場景

new DefaultTabController(length: 3, child: new TabBar(
      tabs: [ "主頁","訂單","個人" ]
      .map( (data)=>new Text(data) ).toList(),

 

(3)didUpdateWidget

當組件的狀態改變的時候就會調用didUpdateWidget,好比調用了setState.實際上這裏flutter框架會建立一個新的Widget,綁定本State,並在這個函數中傳遞老的Widget。這個函數通常用於比較新、老Widget,看看哪些屬性改變了,並對State作一些調整。

 

(4)deactivate

當State對象從樹中被移除時,會調用此回調

 

(5)dispose

一旦到這個階段,組件就要被銷燬了,這個函數通常會移除監聽,清理環境。

 

例子:

假設咱們從A頁面跳轉到B頁面, 那麼A,B頁面的生命週期會是怎樣的呢?


B頁面進入初始化狀態,依次執行4個函數:構造函數 > initState > didChangeDependencies > Widget build , 此時頁面加載完成,進入運行態。
此時A頁面依次執行deactivate > build函數。注意 此時A頁面並未卸載。


而後咱們假設B頁面只有一個按鈕,點擊B頁面中的按鈕,改變按鈕的文字,會執行widget的build方法 ,(理論上也應該執行didUpdateWidget,但我這裏沒有)。


這時,咱們點擊返回鍵從B頁面返回到A頁面。
A頁面從新顯示,B頁面開始卸載。
那麼A先執行deactivate > build , 而後B頁面依次執行:deactivate > dispose 。
此時A頁面進入運行態,B頁面移除
相關文章
相關標籤/搜索