Flutter第7天--字型圖示+綜合小案例+Android程式碼互動

張風捷特烈發表於2018-12-22

Flutter七日遊第七天:2018-12-22 天氣:雨-陰

零、前言

最後一天了,今天將把前六天的零碎知識整合起來,以及未涉及的零碎知識
最後會附上原始碼,在github,我按天分包稍微整理了一下,順手Star一下吧
順便提一下:Dart語法的相關測試在test包的base裡(怕你們找不到)
與Android程式碼互動後感覺flutter還是蠻可以的,可惜沒條件玩ios,不然豈不是可以通殺
(給我七天或許可以把ios跑一圈,以後有錢再說吧)

留圖鎮樓:分類效果和查詢效果
- -
Flutter第7天--字型圖示+綜合小案例+Android程式碼互動
Flutter第7天--字型圖示+綜合小案例+Android程式碼互動

一、字型圖示的相關問題

1.字型圖示:

字型圖示放大不變形,又能改變顏色,主要根據.ttf的字型,
然後圖示算一個文字,根據unicode來對應圖示,就可以用了。
Icon(Icons.android)也許你經常用,但內建圖示有限,只能測試玩玩
實際上用還是需要自定義才行,前端的時候有字型圖示,Flutter應該也行

//比如我們經常怎樣用:
Icon(Icons.comment)
複製程式碼

2.進入原始碼看看:

貌似都是靜態常量,核心在unicode,如0xe577,還有就是字型(MaterialIcons)

///  * [design.google.com/icons](https://design.google.com/icons/)
class Icons {
  Icons._();

  // Generated code: do not hand-edit.
  // See https://github.com/flutter/flutter/wiki/Updating-Material-Design-Fonts
  // BEGIN GENERATED

  /// <i class="material-icons md-36">360</i> &#x2014; material icon named "360".
  static const IconData threesixty = IconData(0xe577, fontFamily: 'MaterialIcons');

  /// <i class="material-icons md-36">3d_rotation</i> &#x2014; material icon named "3d rotation".
  static const IconData threed_rotation = IconData(0xe84d, fontFamily: 'MaterialIcons');

  /// <i class="material-icons md-36">4k</i> &#x2014; material icon named "4k".
  static const IconData four_k = IconData(0xe072, fontFamily: 'MaterialIcons');
複製程式碼

3.怎麼才能自定義字型圖示

玩前端的應該都知道:還是進入阿里圖示神庫:iconfont

Image 3.png


4.根據Flutter內建的類,我寫了一個自動程式碼生成器

雖然直接也能用,不夠要記住圖示的unicode碼,算了,還是跟Flutter看齊吧
注意:為了簡單使用:拷貝到的位置,命名,請務必和下面保持一致!保持一致!
把兩個檔案拷貝到對應處,icon_by_toly.dart寫好(在下面),右鍵執行就自動生成iconfont.dart

程式碼自動生成器.png

程式碼生成器:icon_by_toly.dart

import 'dart:io';

main() {
  var result = """import 'package:flutter/widgets.dart';
//Power By 張風捷特烈--- Generated file. Do not edit.

class TolyIcon {

    TolyIcon._();
""";

  var fileCss = File.fromUri(Uri.parse("${Uri.base}iconfont/iconfont.css"));
  if (!fileCss.existsSync()) {
    return;
  }

  var read = fileCss.readAsStringSync();

  var split = read.split(".icon-");
  split.forEach((str) {
    if (str.contains("before")) {
      var split = str.split(":");
      result += "static const IconData " +
          split[0].replaceAll("-", "_") +
          " = const IconData(" +
          split[2].replaceAll("\"\\", "0x").split("\"")[0] +
          ", fontFamily: \"TolyIcon\");\n";
    }
  });
  result+="}";
   fileCss.delete();

  var fileOut = File.fromUri(Uri.parse("${Uri.base}lib/iconfont.dart"));
  fileOut.writeAsStringSync(result);


  var config="""
  fonts:
    - family: TolyIcon
      fonts:
        - asset: iconfont/iconfont.ttf
  """;
  var yaml = File.fromUri(Uri.parse("${Uri.base}pubspec.yaml"));
  if (yaml.readAsStringSync().contains("TolyIcon")) {
      return;
  }
  yaml.writeAsString(config,mode: FileMode.append);
}
複製程式碼

pubspec.yaml的flutter標籤下也會自動生成配置:
  fonts:
    - family: TolyIcon
      fonts:
        - asset: iconfont/iconfont.ttf
複製程式碼
Icon(TolyIcon.icon_spring_boot)//顏色可自行處理
複製程式碼

執行正常


友情提示:下載之前最好把圖示名字改一下,不然之後找起來費勁
如果實在不想該,可以點選這裡檢視名字和圖示的對應情況

點這個檢視圖示.png


二、綜合小案例

1.初始程式碼:主頁面:android_stack.dart
import 'package:flutter/material.dart';

class AndroidPage extends StatefulWidget {
  @override
  _AndroidPageState createState() => _AndroidPageState();
}

class _AndroidPageState extends State<AndroidPage>
    with SingleTickerProviderStateMixin {


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

  @override
  Widget build(BuildContext context) {

    var scaffold = Scaffold(
      appBar: AppBar(
        title: Text("張風捷特烈"),
      ),
      body: Container(),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          
        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );

    return scaffold;
  }
}
複製程式碼

2.拼接底部條

底部條.gif


2.1:常量的準備:(為了方便使用或修改)
class ItemBean {
  Color color;
  IconData iconId;
  String info;
  ItemBean(this.color, this.iconId, this.info);
}

//底部欄圖示資訊
var iconLi=[
  ItemBean(Color(0xff8FC552),TolyIcon.android,"Android"),
  ItemBean(Color(0xff6BFB00),TolyIcon.icon_spring_boot,"SpringBoot"),
  ItemBean(Color(0xff63DAFF),TolyIcon.react,"React"),
  ItemBean(Color(0xffF3D861),TolyIcon.biji,"程式設計隨筆"),
  ItemBean(Color(0xff5CEBF2),TolyIcon.daima,"系列文章")
];
複製程式碼

2.2:底部欄:
//成員變數
int _curIndex = 0;

//底部欄
var bottomNavigationBar = BottomNavigationBar(
  items: iconLi.map((item) {
    return BottomNavigationBarItem(
        title: Text(
          item.info,
          style: TextStyle(fontSize: 12, color: Colors.black),
        ),
        icon: Icon(
          item.iconId,
          color: item.color,
        ),
        backgroundColor: Color(0xffffffff));
  }).toList(),
  currentIndex: _curIndex,
  onTap: _onTapBNB,
);
複製程式碼

2.3:底部欄點選監聽:_onTapBNB
//底部欄點選監聽
  void _onTapBNB(int position) {
    _curIndex = position;
    setState(() {});
  }
複製程式碼

3:頁面條目:

第五天寫了幾個條目,現在拿來用(詳細分析見第五天,這裡不廢話了)

靜態填充 左側滑欄
Flutter第7天--字型圖示+綜合小案例+Android程式碼互動
Flutter第7天--字型圖示+綜合小案例+Android程式碼互動
3.1:左側滑欄:left_draw.dart
class LeftDrawPage extends StatefulWidget {
  @override
  _LeftDrawPageState createState() => _LeftDrawPageState();
}

class _LeftDrawPageState extends State<LeftDrawPage>
    with SingleTickerProviderStateMixin {
  @override
  Widget build(BuildContext context) {
//左邊頭像
    var headImg3 = Image.asset(
      "images/icon_90.png",
      width: 50,
      height: 50,
    );
//中間的資訊
    var center3 = Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Text(
          "張風捷特烈",
          style: bigStyle,
        ),
        Row(
          children: <Widget>[
            Icon(Icons.next_week, size: 15),
            pd(Text("創世神 | 無"), l: 5)
          ],
        ),
        Row(
          children: <Widget>[
            Icon(Icons.keyboard, size: 15),
            pd(Text("海的彼岸有我未曾見證的風采"), l: 5)
          ],
        ),
      ],
    );
    var rowLine3 = Row(
      children: <Widget>[
        pda(headImg3, 5),
        Expanded(child: pda(center3, 5)),
      ],
    );
    var test3 = Card(
        child: Container(
            height: 95,
            color: Colors.white,
            padding: EdgeInsets.all(5),
            child: rowLine3));
    return Drawer(
        elevation: 5,
        child: Container(
            padding: EdgeInsets.only(top: 50),
            alignment: AlignmentDirectional.topCenter,
            color: Color(0xff99C6F9),
            child: test3));
  }
}
複製程式碼

3.2:列表靜態填充:home_list.dart
class HomeListPage extends StatefulWidget {
  @override
  _HomeListPageState createState() => _HomeListPageState();
}

class _HomeListPageState extends State<HomeListPage> {
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: 10,
      itemBuilder: (BuildContext context, int index) {
        return renderItem(index);
      },
    );
  }

  renderItem(int index) {
    ////////////////////////-----------------測試4--------------------------------
    var line1_4 = Row(
      children: <Widget>[
        Image.asset("images/icon_90.png", width: 20, height: 20),
        Expanded(
          child: pd(Text("張風捷特烈"), l: 5),
        ),
        Text(
          "Flutter/Dart",
          style: infoStyle,
        )
      ],
    );

    var center_right = Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        Text(
          "Flutter第4天--基礎控制元件(下)+Flex佈局詳解",
          style: littelStyle,
          maxLines: 2,
        ),
        pd(
            Text(
              "1.2:優雅地檢視:圖片的適應模式--BoxFit1.3:優雅地檢視:顏色混合模式--colorBlendMode",
              style: infoStyle,
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
            t: 5),
      ],
    );

//中間的資訊
    var center4 = Row(
      children: <Widget>[
        Expanded(child: pda(center_right, 5)),
        Image.asset(
          "images/wy_300x200.jpg",
          width: 80,
          height: 80,
          fit: BoxFit.fitHeight,
        )
      ],
    );

    var end4 = Row(
      children: <Widget>[
        Icon(
          Icons.grade,
          color: Colors.green,
          size: 20,
        ),
        Text(
          "1000W",
          style: infoStyle,
        ),
        pd(Icon(Icons.tag_faces, color: Colors.lightBlueAccent, size: 20),
            l: 15, r: 5),
        Text("2000W", style: infoStyle),
      ],
    );

    var item4 = Column(
      children: <Widget>[line1_4, Expanded(child: center4), end4],
    );

    var aCard = Card(
        child: Container(
            height: 160,
            color: Colors.white,
            padding: EdgeInsets.all(10),
            child: item4));

    return aCard;
  }
}
複製程式碼

4.動態資料獲取:

昨天已經把http獲取資料的內容將過了,並且把服務端的資料解析了
今天就是使用這些資料,來填充靜態介面,api介面介紹NoteBean昨天已完成
封裝一個獲取資料的方法:簡單說下用法:
style是型別:Android是A ;SpringBoot是SB ; React 是Re ; 筆記是 Note
offset和num 聯合使用可以達到分頁效果, 比如offset=24,num=12,就是一頁12條資料的第3頁

import 'dart:convert';

import 'package:http/http.dart' as client;
import 'package:toly/pager/day7/bean.dart';

const BASE_URL = 'http://192.168.43.60:8089';//api介面的域名自己改一下
const API = '/api/android/note/';

Future<List<NoteBean>> get({style = '', offset = 0, num = 1}) async {
  var dataLi = <NoteBean>[];
  var url = BASE_URL + API + style + "/" + "$offset" + "/" + "$num";
  try {
    final response = await client.get(url);
    if (response.statusCode == 200) {
      var result = ResultBean.fromJson(json.decode(response.body));
      List data = result.data;
      print(NoteBean.fromJson(data[0]).type);
      for (int i = 0; i < data.length; i++) {
        dataLi.add(NoteBean.fromJson(data[i]));
      }
      return dataLi;
    }
  } catch (e) {
    print(e);
  }
}
複製程式碼

5.用一個資料來進行填充測試:

主頁面:android_stack.dart,initState的時候獲取資料,並更新狀態

動態獲取資料填充.png

//定義一個成員變數
  List<NoteBean> _notes = [];
  
  @override
void initState() {
  super.initState();

  get(num: 1).then((beanLi) {
    _notes = beanLi;
    setState(() {});
  });
}
複製程式碼

列表介面:home_list.dart:接收主介面傳來的_notes,並渲染資料

class HomeListPage extends StatefulWidget {
  List<NoteBean> _notes;
  HomeListPage(List<NoteBean> notes) {
    _notes = notes;
  }
  @override
  _HomeListPageState createState() => _HomeListPageState();
}

class _HomeListPageState extends State<HomeListPage> {
  @override
  Widget build(BuildContext context) {
    var notes = widget._notes;
    
    return ListView.builder(
      itemCount: notes.length,
      itemBuilder: (BuildContext context, int index) {
        return renderItem(notes[index]);
      },
    );
  }
    //渲染條目
  renderItem(NoteBean note) {
    var line1_4 = Row(
      children: <Widget>[
        Image.asset("images/icon_90.png", width: 20, height: 20),
        Expanded( child: pd(Text("張風捷特烈"), l: 5),),
        Text( note.type,style: infoStyle,)
        ],
    );
    var center_right = Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[Text(note.name,style: littelStyle,maxLines: 2,),
        pd(Text( note.info, style: infoStyle, maxLines: 2,
              overflow: TextOverflow.ellipsis, ), t: 5),
      ],
    );

//中間的資訊
    var center4 = Row(
      children: <Widget>[
        Expanded(child: pda(center_right, 5)),
        Image.network( note.imgUrl,
          width: 80, height: 80, fit: BoxFit.fitHeight )
      ],
    );

    var end4 = Row(
      children: <Widget>[
        Icon( Icons.grade, color: Colors.green, size: 20, ),
        Text( "1000W", style: infoStyle,),
        pd(Icon(Icons.tag_faces, color: Colors.lightBlueAccent, size: 20),
            l: 15, r: 5),
        Text("2000W", style: infoStyle),
      ],
    );

    var item4 = Column(
      children: <Widget>[line1_4, Expanded(child: center4), end4],
    );

    var aCard = Card(
        child: Container(  height: 160,color: Colors.white,
            padding: EdgeInsets.all(10), child: item4));
    return aCard;
  }
}
複製程式碼

現在萬事俱備,東風也到了,num小小動一下:num=30

-- --
Flutter第7天--字型圖示+綜合小案例+Android程式碼互動
Flutter第7天--字型圖示+綜合小案例+Android程式碼互動

也許你感覺還未開始,但確實已經結束了...


6.底部導航欄的切換:(下面兩個圖一樣的,為了撐場面...)

剛才是資料沒有分型別,現在點選底部導航,按範圍進行展示
get(style: "area/A", num: 30)//這樣就是展示又有安卓類的文章

- -
Flutter第7天--字型圖示+綜合小案例+Android程式碼互動
Flutter第7天--字型圖示+綜合小案例+Android程式碼互動

android_stack.dart新增成員變數
這裡我預設載入完,做分頁的話,再新增個_count的成員變數就行了

String style = "area/A";

//頁面開啟,預設載入安卓頁
  @override
  void initState() {
    super.initState();
    get(style: style, num: 1000).then((beanLi) {
      _notes = beanLi;
      setState(() {});
    });
  }
  
  //底部欄點選監聽---動態改變範圍
  void _onTapBNB(int position) {
    switch (position) {
      case 0:
        style = "area/A";
        break;
      case 1:
        style = "area/SB";
        break;
      case 2:
        style = "area/Re";
        break;
      case 3:
        style = "area/Note";
        break;
      case 4:
        style = "area/A";
        break;
    }
    _curIndex = position;
    get(style: style, num: 1000).then((beanLi) {
      _notes = beanLi;
      setState(() {});
    });
  }
複製程式碼

7.底部欄和搜尋功能

底部欄用法詳情在第四篇

-- --
底部欄.gif
搜尋功能.gif

底部欄:這裡把事件寫在裡面了,你也可以抽成方法
或者有些控制元件太長,你也可以抽出來做變數

var searchSheet = BottomSheet(
    onClosing: () {},
    builder: (context) => (Card(
        color: Color.fromARGB(255, 214, 242, 251),
        child: Wrap(
          children: <Widget>[
            Center(child: pdhv(TextField(
              onChanged: (v) {style = "name/" + v;}), h: 60)),
            Center(child: pdhv( GestureDetector(child:
            Image.asset("images/icon_90.png",width: 50,height: 50 ),
                      onTap: () {
                        get(style: style, num: 1000).then((beanLi) {
                          _notes = beanLi;
                          setState(() {});
                        });
                      },
                    ),
                    v: 10)),
          ],
        ))));
        
//點選按鈕彈出:
 var scContext; //先宣告一下Scaffold的context
    var scaffold = Scaffold(
        appBar: AppBar(
          title: Text("張風捷特烈"),
        ),
        body: Builder(builder: (context) {
          scContext = context;
          return HomeListPage(_notes);
        }),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            Scaffold.of(scContext).showBottomSheet(searchSheet.builder);
          },
          //下面不用修改,略...

複製程式碼

Ok,小案例就這樣


三、Android程式碼互動

1.最簡單的無參無返回函式呼叫:兩對應

不得不說:前六天不能彈吐司真是不好受,原生互動肯定先拿他開刀

toast


1.1:Android程式碼
public class MainActivity extends FlutterActivity {
    private static final String CHANNEL = "www.toly1994.com/test.名字隨意起";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        GeneratedPluginRegistrant.registerWith(this);

        new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
                new MethodChannel.MethodCallHandler() {
                    @Override
                    public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
                        if (methodCall.method.equals("showToast")) {
                            showToast("Hello Flutter,I am in Android");
                        } else {
                            result.notImplemented();
                        }
                    }
                }
        );
    }
    /**
     * 顯示吐司
     *
     * @param msg 資訊
     */
    public void showToast(String msg) {
        Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
        toast.show();
    }
}
複製程式碼
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

const platform = const MethodChannel("www.toly1994.com/test.名字隨意起");

var toastTest = Center(
  child: RaisedButton(
    onPressed: () {
      platform.invokeMethod("showToast");
    },
    child: new Text("點選彈吐司"),
  ),
);

複製程式碼

兩個對應.png


2.Flutter中傳參,呼叫Android含參方法:三對應

toast含參呼叫


2.1:Android程式碼
public class MainActivity extends FlutterActivity {
    private static final String CHANNEL = "www.toly1994.com/test.名字隨意起";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        GeneratedPluginRegistrant.registerWith(this);

        new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
                new MethodChannel.MethodCallHandler() {
                    @Override
                    public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
                        if (methodCall.method.equals("showToast")) {
                            //解析引數
                            String msg = methodCall.argument("msg");
                            showToast(msg);
                        } else {
                            result.notImplemented();
                        }
                    }
                }
        );
    }

    /**
     * 顯示吐司
     *
     * @param msg 資訊
     */
    public void showToast(String msg) {
        Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
        toast.show();
    }
}
複製程式碼

2.2:Flutter程式碼:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

const platform = const MethodChannel("www.toly1994.com/test.名字隨意起");

var toastTest = Center(
  child: RaisedButton(
    onPressed: () {
      platform.invokeMethod("showToast",{"msg":"Flutter大爺我賞你一口吐司"});
    },
    child: new Text("點選彈吐司"),
  ),
);
複製程式碼

加引數.png


2.3:加返回值的方法呼叫:

舉什麼例子,我想了一會,就來個MD5碼吧

呼叫Md5函式返回結果.gif

//Activity新增判斷分支
if (methodCall.method.equals("getMD5")) {
    String arg = methodCall.argument("arg");
    String md5 = getMD5(arg);
    result.success(md5);
}

    /**
     * 獲取一個字串的Md5值
     *
     * @param content 內容
     * @return Md5值
     */
    public String getMD5(String content) {
        content = content + "芝麻開門";
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(content.getBytes());
            return getHashString(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String getHashString(MessageDigest digest) {
        StringBuilder builder = new StringBuilder();
        for (byte b : digest.digest()) {
            builder.append(Integer.toHexString((b >> 4) & 0xf));
            builder.append(Integer.toHexString(b & 0xf));
        }
        return builder.toString();
    }

複製程式碼
2.2:Flutter程式碼:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

const platform = const MethodChannel("www.toly1994.com/test.名字隨意起");

var toastTest = Center(
  child: RaisedButton(
    onPressed: () {

      var result= platform.invokeMethod("getMD5",{"arg":"https://www.jianshu.com/p/9bac0072d1a0"});
      result.then((str){
        platform.invokeMethod("showToast",{"msg":str});
      });

    },
    child: new Text("點選彈吐司"),
  ),
);
複製程式碼

基本上也就這三種情況


[彩蛋]--以前Mark的一個小點:Card的shape

有人說學習的時候一個問題會牽扯到很多其他的問題,問題一多就無從下手
我只說一個字:"棧":來最後一波學習看原始碼的方法了,走起

預設卡片.png


1.shape是什麼:形狀

現在的問題棧

Flutter第7天--字型圖示+綜合小案例+Android程式碼互動

可見預設圓角是4的RoundedRectangleBorder

---->[shape屬性]----
/// The default shape is a [RoundedRectangleBorder] with a circular corner
/// radius of 4.0.
final ShapeBorder shape;

---->[RoundedRectangleBorder]----
 const RoundedRectangleBorder({
    this.side = BorderSide.none,
    this.borderRadius = BorderRadius.zero,
    
//可見有兩個屬性:BorderSide和BorderRadius

---->[BorderSide]----
class BorderSide {
  /// Creates the side of a border.
  ///
  /// By default, the border is 1.0 logical pixels wide and solid black.
  const BorderSide({
    this.color = const Color(0xFF000000),
    this.width = 1.0,
    this.style = BorderStyle.solid,

---->[BorderRadius]----
class BorderRadius extends BorderRadiusGeometry {
  /// Creates a border radius where all radii are [radius].
  const BorderRadius.all(Radius radius) : this.only(
    topLeft: radius,
    topRight: radius,
    bottomLeft: radius,
    bottomRight: radius,
  );

  /// Creates a border radius where all radii are [Radius.circular(radius)].
  BorderRadius.circular(double radius) : this.all(
    Radius.circular(radius),
  );
  
---->[Radius]------
class Radius {
  /// Constructs a circular radius. [x] and [y] will have the same radius value.
  const Radius.circular(double radius) : this.elliptical(radius, radius);

  /// Constructs an elliptical radius with the given radii.
  const Radius.elliptical(this.x, this.y);

  /// The radius value on the horizontal axis.
  final double x;

  /// The radius value on the vertical axis.
  final double y;

複製程式碼

一個shape牽扯出這麼多類,有人可能就棧溢位了,還是使用預設的吧,等一下,且聽我分析
當Radius入問題棧之後,看一下也就是兩個值,就出棧了,BorderRadius跟著也出棧了
BorderSide三個欄位,看一下,出棧了,現在棧頂是RoundedRectangleBorder你還不會嗎?

Flutter第7天--字型圖示+綜合小案例+Android程式碼互動

2. RoundedRectangleBorder改變圓角大小+邊線

紫邊.png

var card_shape = Card(
//    shape: CircleBorder(side: BorderSide(width: 1)),
    shape: RoundedRectangleBorder(
      side:BorderSide(color: Color(0xffD516F5),width: 5) ,
        borderRadius: BorderRadius.all(Radius.circular(20))),
    clipBehavior: Clip.antiAlias,
    child: Container(
      width: 100,
      height: 100,
      color: Color(0xffCDECF6),
      child: Center(child:Text(
        "捷",
        style: TextStyle(color: Colors.black,fontSize: 40),
      ) ,),
    ));

複製程式碼

那彈棧過後問題跑哪裡?
我想應該是臨時知識庫吧,你解決的問題中獲取的知識,經驗會累積
可能長久不用知識庫裡的知識會漏掉,但印象有的,下一次再入棧,解決起來會更快
在的知識庫裡紮根的知識,那當你遇到時,就不是問題,直接彈棧,這樣想學習是不是也挺好玩的

Flutter第7天--字型圖示+綜合小案例+Android程式碼互動

大神級的Coder知識庫豐富,問題都不是問題,也許偶爾入棧一兩個,但棧很深(感覺挺浪費哈)
新手就是棧比較淺,問題多,所以容易StackOver,所以修煉你容忍問題的能力(棧深)很有必要
像我這樣不深不淺的剛剛好,會碰到問題,也能一點點解決,一點一點踏上封神之路
但所有的大神也都是從新手這樣過來的,解決問題的能力也不是與生俱來,祝你慢慢彈棧,收穫多多。


3.接下來看ShapeBorder在棧頂,我們去瞅瞅

BorderSide現在已經化敵為友,CircleBorder豈不是秒出棧,並且俘獲CircleBorder一枚
而且BorderSide強化+1,知識就是這樣積累的,難道還有別的方法嗎?除非記憶拷貝...

Flutter第7天--字型圖示+綜合小案例+Android程式碼互動

轉一轉當CD背景感覺挺不錯

Flutter第7天--字型圖示+綜合小案例+Android程式碼互動

var card_shape = Card(
    shape: CircleBorder(side: BorderSide(width: 15,color: Color(0xffF9DFA7))),
    clipBehavior: Clip.antiAlias,
    child: Container(
      width: 100,
      height: 100,
      color: Color(0xffCDECF6),
      child: Center(child:Text(
        "捷",
        style: TextStyle(color: Colors.black,fontSize: 40),
      ) ,),
    ));
複製程式碼

4.前方高能,非戰鬥人員帶好零食

其實覺得shape好玩,是在粗略看原始碼時,看到了canvas,才mark的
自定義ShapeBorder走起:畫具在手,天下我有

捷.png

var card_shape = Card(
    shape: StarBorder(),
//    shape: CircleBorder(side: BorderSide(width: 15,color: Color(0xffF9DFA7))),
//    shape: RoundedRectangleBorder(
//      side:BorderSide(color: Color(0xffD516F5),width: 5) ,
//        borderRadius: BorderRadius.all(Radius.circular(20))),
    clipBehavior: Clip.hardEdge,
    child: Container(
      width: 100,
      height: 100,
      color: Color(0xffCDECF6),
      child: Center(
        child: Text(
          "捷",
          style: TextStyle(color: Colors.black, fontSize: 40),
        ),
      ),
    ));

class StarBorder extends ShapeBorder {
  @override
  // TODO: implement dimensions
  EdgeInsetsGeometry get dimensions => null;

  @override
  Path getInnerPath(Rect rect, {TextDirection textDirection}) {
    // TODO: implement getInnerPath
    return null;
  }

  @override
  Path getOuterPath(Rect rect, {TextDirection textDirection}) {
    print(rect.right);
    return regularPolygonPath(10, 50,x: rect.height/2,y: rect.width/2);
  }

  @override
  void paint(Canvas canvas, Rect rect, {TextDirection textDirection}) {
    canvas.translate(50, 50);
//    canvas.drawPath(nStarPath(5, 40, 20), new Paint());
  }

  @override
  ShapeBorder scale(double t) {
    // TODO: implement scale
    return null;
  }
}
複製程式碼
路徑封裝(稍微優化了一下)
/**
 * n角星路徑
 *
 * @param num 幾角星
 * @param R   外接圓半徑
 * @param r   內接圓半徑
 * @return n角星路徑
 */
Path nStarPath(int num, double R, double r, {x = 0, y = 0}) {
  Path path = new Path();
  double perDeg = 360 / num; //尖角的度數
  double degA = perDeg / 2 / 2;
  double degB = 360 / (num - 1) / 2 - degA / 2 + degA;

  path.moveTo(cos(_rad(degA)) * R+x, (-sin(_rad(degA)) * R+y));
  for (int i = 0; i < num; i++) {
    path.lineTo(
        cos(_rad(degA + perDeg * i)) * R+x, -sin(_rad(degA + perDeg * i)) * R+y);
    path.lineTo(
        cos(_rad(degB + perDeg * i)) * r+x, -sin(_rad(degB + perDeg * i)) * r+y);
  }
  path.close();
  return path;
}

/**
 * 畫正n角星的路徑:
 *
 * @param num 角數
 * @param R   外接圓半徑
 * @return 畫正n角星的路徑
 */
Path regularStarPath(int num, double R,{x = 0, y = 0}) {
  double degA, degB;
  if (num % 2 == 1) {
    //奇數和偶數角區別對待
    degA = 360 / num / 2 / 2;
    degB = 180 - degA - 360 / num / 2;
  } else {
    degA = 360 / num / 2;
    degB = 180 - degA - 360 / num / 2;
  }
  double r = R * sin(_rad(degA)) / sin(_rad(degB));
  return nStarPath(num, R, r,x: x,y:y);
}

/**
 * 畫正n邊形的路徑
 *
 * @param num 邊數
 * @param R   外接圓半徑
 * @return 畫正n邊形的路徑
 */
Path regularPolygonPath(int num, double R,{x = 0, y = 0}) {
  double r = R * cos(_rad(360 / num / 2)); //!!一點解決
  return nStarPath(num, R, r,x: x,y:y);
}

/**
 * 角度制化為弧度制
 *
 * @param deg 角度
 * @return 弧度
 */
double _rad(double deg) {
  return deg * pi / 180;
}
複製程式碼

師傅領進門,修行在個人,我已經把功力傳給你了,能否修成正果,就看各自造化。
事了拂衣去,深藏功與名,Ok,Flutter七日遊,完散花,自認為沒有爛尾,耶!


後記:捷文規範

1.本文成長記錄及勘誤表
專案原始碼 日期 備註
V0.1-github 2018-12-22 Flutter第7天--字型圖示+綜合小案例+Android程式碼互動
2.更多關於我
筆名 QQ 微信 愛好
張風捷特烈 1981462002 zdl1994328 語言
我的github 我的簡書 我的掘金 個人網站
3.宣告

1----本文由張風捷特烈原創,轉載請註明
2----歡迎廣大程式設計愛好者共同交流
3----個人能力有限,如有不正之處歡迎大家批評指證,必定虛心改正
4----看到這裡,我在此感謝你的喜歡與支援


icon_wx_200.png

相關文章