何时使用 new() 和 make()

  • 切片、映射和通道,使用 make
  • 数组、结构体和所有的值类型,使用 new
2021/07/03 posted in  Golang

Flutter 12 大常用模块

也就是说整个 flutter 按照功能或者能力分为 12 个大的模块,模块内部具体的实现根据需要的能力会引用其他模块

animation.dart:动画模块
cupertino.dart:ios design 风格模块
foundation.dart:底层工具模块
gesture.dart:手势识别模块
material.dart:android material design 风格模块
painting.dart:flutter 绘制引擎模块,包含各种绘制 api,比如缩放图片、阴影插值,绘制边框等等
physics.dart:简单一维物理模拟模块,比如弹簧、摩擦、重力等,用于用户界面动画
rendering.dart:flutter RenderObjuect 渲染树模块,提供给 wieget 模块使用,实现其后端的布局和绘制
scheduler.dart:调度模块,负责程序框架回调以及特定优先级任务的调度
semantics.dart:语意模块,SemanticsEvent 类定义了平台的语意事件的发送协议,SemanticsNode层级表示了UI的语意结构,用于特定平台的加速服务
services.dart:平台能力服务,整个模块只引用了 core dart 库以及 foundation模块
widgets.dart:flutter 的 widgets 框架
2020/04/11 posted in  Flutter

Flutter 笔记

生成模型类

flutter packages pub run build_runner build --delete-conflicting-outputs
2019/12/22 posted in  Flutter

Gradle 注意项

Android Studio 的 gradle 插件版本依赖对照表
https://developer.android.google.cn/studio/releases/gradle-plugin#updating-plugin

Gradle 的全局代理设置是在:~/.gradle/gradle.properties

# proxy
#systemProp.https.proxyHost=127.0.0.1
#systemProp.https.proxyPort=1086
#systemProp.http.proxyHost=127.0.0.1
#systemProp.http.proxyPort=1086

org.gradle.jvmargs=-DsocksProxyHost=127.0.0.1 -DsocksProxyPort=1086

项目下的 android目录下的 build.gradle 文件修改

把 google() 和 jcenter()注释掉,换成阿里云的:

buildscript {
    repositories {
        //google()
        //jcenter()
        //maven { url 'http://developer.huawei.com/repo/' }
        maven { url 'https://maven.aliyun.com/repository/google' }
        maven { url 'https://maven.aliyun.com/repository/jcenter' }
        maven { url 'https://maven.aliyun.com/repository/public' }
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'
    }
}

allprojects {
    repositories {
        //google()
        //jcenter()
        //maven { url 'http://developer.huawei.com/repo/' }
        maven { url 'https://maven.aliyun.com/repository/google' }
        maven { url 'https://maven.aliyun.com/repository/jcenter' }
        maven { url 'https://maven.aliyun.com/repository/public' }
    }
}

flutter 下的 flutter.gradle 文件 修改

路径在 ~/flutter/packages/flutter_tools/gradle/flutter.gradle

buildscript {
    repositories {
        //google()
        //jcenter()
        maven { url 'https://maven.aliyun.com/repository/google' }
        maven { url 'https://maven.aliyun.com/repository/jcenter' }
        maven { url 'https://maven.aliyun.com/repository/public' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'
    }
}
2018/12/12 posted in  Flutter

熟悉Dart语言

本文是 Flutter 学习指南的第4篇,假定读者有一定的编程经验。通过快速浏览 Dart 的一些基础特性,让读者具备使用它进行开发的基本能力。

##变量

基本类型

bool done = true;
int num = 2;
double x = 3.14;

final bool visible = false;
final int amount = 100;
final double y = 2.7;

const bool debug = true;
const int sum = 42;
const double z = 1.2;

跟常用的其他语言不同,Dart 没有 byte、char 和 float,int、double 都是 64 位。final 跟 Java 里的 final 一样,表示一个运行时常量(在程序运行的时候赋值,赋值后值不再改变)。const 表示一个编译时常量,在程序编译的时候它的值就确定了。

如果你觉得每次写变量类型太麻烦,你应该会喜欢 Dart 的类型推断功能:


var done = true;
var num = 2;
var x = 3.14;

final visible = false;
final amount = 100;
final y = 2.7;

const debug = true;
const sum = 42;
const z = 1.2;

Dart 里所有的东西都是对象,包括 int、函数。

String

var str = ' foo';
var str2 = str.toUpperCase();
var str3 = str.trim();
assert(str == str2);
assert(!identical(str, str2));

Dart 里的 String 跟 Java 中的一样,是不可变对象;不同的是,检测两个 String 的内容是否一样事,我们使用 == 进行比较;如果要测试两个对象是否是同一个对象(indentity test),使用 identical 函数。

List、Map 和 Set

List

// 使用构造函数创建对象
// 跟 var list = new List<int>(); 一样
var list = List<int>();
list.add(1);
list.add(2);


// 通过字面量创建对象,list 的泛型参数可以从变量定义推断出来。
// 推荐使用字面量方式创建对象
var list2 = [1, 2];
// 没有元素,显式指定泛型参数为 int
var list3 = <int>[];
list3.add(1);
list3.add(2);

var list4 = const[1, 2];
// list4 指向的是一个常量,我们不能给它添加元素(不能修改它)
list4.add(3);       // error
// list4 本身不是一个常量,所以它可以指向另一个对象
list4 = [4, 5];     // it's fine

const list5 = [1, 2];
// 相当于 const list5 = const[1, 2];
list5.add(3);       // error

// Dart 同样提供了 for-in 循环。
// 因为语音设计时就考虑到了这个需求,in 在 Dart 里

是一个关键字

var list6 = [1, 3, 5, 7];
for (var e in list6) {
  print(e);
}

在 Dart 2 里,创建对象时可以省略 new 关键字,也推荐省略 new。

Set

var set = Set<String>();
set.add('foo');
set.add('bar');
assert(set.contains('foo'));

我们只能通过 Set 的构造函数创建实例。

Map

var map = Map<String, int>();
// 添加
map['foo'] = 1;
map['bar'] = 3;
// 修改
map['foo'] = 4;
// 对应的 key 不存在时,返回 null
if (map['foobar'] == null) {
  print('map does not contain foobar');
}

var map2 = const {
  'foo': 2,
  'bar': 4,
};
var map3 = <String, String>{};

dynamic 和 Object
前面我们说过,Dart 里所有东西都是对象。所有这些对象的父类就是 Object。

Object o = 'string';
o = 42;
o.toString();   // 我们只能调用 Object 支持的方法

dynamic obj = 'string';
obj['foo'] = 4;  // 可以编译通过,但在运行时会抛出 NoSuchMethodError

Object 和 dynamic 都使得我们可以接收任意类型的参数,但两者的区别非常的大。

使用 Object 时,我们只是在说接受任意类型,我们需要的是一个 Object。类型系统会保证其类型安全。

使用 dynamic 则是告诉编译器,我们知道自己在做什么,不用做类型检测。当我们调用一个不存在的方法时,会执行 noSuchMethod() 方法,默认情况下(在 Object 里实现)它会抛出 NoSuchMethodError。

为了在运行时检测进行类型检测,Dart 提供了一个关键字 is:

dynamic obj = <String, int>{};
if (obj is Map<String, int>) {
  // 进过类型判断后,Dart 知道 obj 是一个 Map<String, int>,
  // 所以这里不用强制转换 obj 的类型,即使我们声明 obj 为 Object。
  obj['foo'] = 42;
}

// 虽然 Dart 也提供了 as 让我们进行类型的强制转换,但为了进来更安全
// 的转换,更推荐使用 is
var map = obj as Map<String, int>;

语句

var success = true;
if (success) {
  print('done');
} else {
  print('fail');
}

for (var i = 0; i < 5; ++i) {
  print(i);
}

var sum = 0;
var j = 1;
do {
  sum += j;
  ++j;
} while (j < 5);

while (sum-- > 0) {
  print(sum);
}

var type = 1;
switch (type) {
  case 0:
    // ...
    break;
  case 1:
    // ..
    break;
  case 2:
    // ...
    break;
  default:
    // ...
    break;
}

常见的 if/else,do while,while 和 switch 在 Dart 里面都支持。switch 也支持 String 和 enum。

函数

最普通的函数看起来跟 Java 里的一样:


int foo(int x) {
  return 0;
}
Dart 也支持可选参数:

void main() {
  print(foo(2));
  print(foo(1, 2));
}

int foo(int x, [int y]) {
  // 是的,int 也可以是 null
  if (y != null) {
    return x + y;
  }
  return x;
}

// 结果:
// 2
// 3

默认参数也是支持的:

int foo(int x, [int y = 0]) {
  return x + y;
}

还能用具名参数(named parameters):

void main() {
  print(foo(x: 1, y: 2));
  // 具名参数的顺序可以是任意的
  print(foo(y: 3, x: 4));
  // 所有的具名参数都是可选的,这个调用是合法的,但它会导致 foo() 在运行时抛异常
  print(foo());
}

int foo({int x, int y}) {
  return x + y;
}

具名参数也可以有默认参数:

void main() {
  print(foo(x: 1, y: 2));
  print(foo());
}

int foo({int x = 0, int y = 0}) {
  return x + y;
}

如果想告诉用户某个具名参数是必须的,可以使用注解 @required:

int foo({@required int x, @required int y}) {
  return x + y;
}
@required 是 meta 包里提供的 API,更多的信息读者可以查看 https://pub.dartlang.org/packages/meta。

函数还可以在函数的内部定义:

// typedef 在 Dart 里面用于定义函数类型的别名
typedef Adder = int Function(int, int);

Adder makeAdder(int extra) {
  int adder(int x, int y) {
    return x + y + extra;
  }
  return adder;
}

void main() {
  var adder = makeAdder(2);
  print(adder(1, 2));
}

// 结果:
// 5

像上面这样简单的函数,我们还可以使用 lambda:

typedef Adder = int Function(int, int);

Adder makeAdder(int extra) {
  return (int x, int y) {
    return x + y + extra;
  };
  // 如果只有一个语句,我们可以使用下面这种更为简洁的形式
  // return (int x, int y) => x + y + extra;
}

void main() {
  var adder = makeAdder(2);
  print(adder(1, 2));
}

Dart 里面不仅变量支持类型推断,lambda 的参数也支持自动推断。上面的代码还可以进一步简化为:

typedef Adder = int Function(int, int);

Adder makeAdder(int extra) {
  // 我们要返回的类型是 Adder,所以 Dart 知道 x, y 都是 int
  return (x, y) => x + y + extra;
}

void main() {
  var adder = makeAdder(2);
  print(adder(1, 2));
}

美中不足的是,Dart 不支持函数的重载。

异常

抛出异常:

throw Exception('put your error message here');

捕获异常:

try {
  // ...
// 捕获特定类型的异常
} on FormatException catch (e) {
  // ...
// 捕获特定类型的异常,但不需要这个对象
} on Exception {
  // ..
// 捕获所有异常
} catch (e) {
  // ...
} finally {
  // ...
}

跟 Java 不同的是,Dart 可以抛出任意类型的对象:

throw 42;

定义一个类:

class Point2D {
  static const someConst = 2;

  int x;
  // 成员变量也可以是 final 的
  final int y;

  Point2D(int x, int y) {
    this.x = x;
    this.y = y;
  }
}

由于这种初始化方式很常见,Dart 提供了更简洁的方式:

class point2d {
  int x;
  int y;

  point2d(this.x, this.y);
}

此外,还可以使用初始化列表(initializer list)对对象进行初始化:

class Point2D {
  int x;
  int y;

  // 由于是在 initializer list 中,Dart 知道第一个 x 是 this.x,
  // 第二个 x 是构造函数的参数
  Point2D(int x, int y) : x = x, y = y {
    // ...
  }
}

initializer list 会在构造函数的函数体运行前执行。

Dart 具有垃圾收集功能,对象的使用跟 Java 里几乎是一样的:

main() {
  var point = Point2D(1, 2);
  point.x = 4;
  print(point);
}

class Point2D {
  int x;
  int y;
  Point2D(this.x, this.y);

  // 所有的类都继承自 Object,toString() 是 Object 中的方法
  @override
  String toString() {
    // 在字符串的内部可以通过 ${expression} 的方式插入值,如果
    // expression 是一个变量,可以省略花括号
    return "Point2D{x=$x, y=$y}";
  }
}

// 结果:
// Point2D{x=4, y=2}

Dart 使用 package 的概念来管理源码和可见性。它没有 public、private 之类的访问权限控制符,默认情况下,所有的符号都是公开的。如果我们不想某个变量对包的外部可见,可以使用下划线开头来给变量命名。

class _Foo {
  // ...
}

class Bar {
  int _x;
}

下面我们使用 Dart 的访问控制,实现一个带偏移量的 Point:


class OffsetPoint {
  int _x;
  int _y;
  int offset;

  OffsetPoint(int x, int y, int offset)
      : _x = x, _y = y, offset = offset {}

  // 定义一个 getter
  int get x => _x + offset;
  // getter 不能有参数,连括号都省掉了
  int get y {
    return _y + offset;
  }
  // 定义 setter
  void set x (int x) => _x = x;
  void set y (int y) => _y = y;

  @override
  String toString() {
    return "OffsetPoint{x=$x, y=$y}";
  }
}

main() {
  var point = OffsetPoint(1, 2, 10);
  // 使用 getter/setter 时,就像它是一个普通的成员变量
  print(point.x)
  print(point);
  point.x = 4;
  print(point);
}

// 结果:
// 11
// OffsetPoint{x=11, y=12}
// OffsetPoint{x=14, y=12}

在 Dart 里继承对象也很简单:

class Point2D {
  int x;
  int y;
  Point2D(this.x, this.y);
}

class Point3D extends Point2D {
  int z;
  // 父类的构造函数只能在 initializer list 里调用
  Point3D(int x, int y, int z): z = z, super(x, y) {
  }
}

但是对象构造时它跟 Java、C++ 都不太一样:

先执行子类 initializer list,但只初始化自己的成员变量

初始化父类的成员变量

执行父类构造函数的函数体

执行之类构造函数的函数体

基于这个初始化顺序,推荐是把 super() 放在 initializer list 的最后。此外,在 initializer list 里不能访问 this(也就是说,只能调用静态方法)。

虽然 Dart 是单继承的,但它也提供了一定程度的多重继承支持:


abstract class Bark {
  void bark() {
    print('woof');
  }
}

class Point3D extends Point2D with Bark {
  int z;
  // 父类的构造函数只能在 initializer list 里调用
  Point3D(int x, int y, int z): z = z, super(x, y) {
  }
}

// 没有其他类需要继承,所以直接 extends Bark 就可以了
class Foo extends Bark {}

void main() {
  var p = Point3D(1, 2, 3);
  p.bark();
}

Dart 把支持多重继承的类叫做 mixin。更详细的介绍,读者可以参考https://www.dartlang.org/articles/language/mixins。

泛型

class Pair<S, T> {
  S first;
  T second;
  Pair(this.first, this.second);
}

void main() {
  var p = Pair('hello', 2);
  print(p is Pair<String, int>);
  // is! 也是 Dart 的运算符,下面的语句跟 !(p is Pair<int, int>) 是一样的,
  // 但 is! 读起来跟像英语
  print(p is! Pair<int, int>);
  print(p is Pair);
}

// 结果:
// true
// true
// true

跟 Java 不同,Dart 的泛型参数类型在运行时是保留的。

Future

Dart 是单线程的,主线程由一个事件循环来执行(类似 Android 的主线程)。对于异步代码,我们通过 Future 来获取结果:

import 'dart:io';

void foo() {
  var file = File('path-to-your-file');
  file.exists()
      .then((exists) => print('file ${exists ? 'exists' : 'not exists'}'))
      .catchError((e) => print(e));
}
Dart 2 提供了 async 函数,用来简化这种编程范式。下面这段代码的效果跟上面是一样的:

void foo() async {
  var file = File('path-to-your-file');
  try {
    var exists = await file.exists();
    print('file ${exists ? 'exists' : 'not exists'}');
  } catch (e) {
    print(e);
  }
}

但是要注意,上面两段代码并不是完全一样的:

// import 语句用于导入一个包
import 'dart:io';

void main() {
  foo();
  bar();
}

void bar() {
  var file = File('path-to-your-file');
  file.exists()
      .then((exists) => print('bar: file ${exists ? 'exists' : 'not exists'}'))
      .catchError((e) => print(e));
  print('bar: after file.exists() returned');
}

void foo() async {
  var file = File('path-to-your-file');
  try {
    var exists = await file.exists();
    print('bar: file ${exists ? 'exists' : 'not exists'}');
    print('bar: after file.exists() returned');
  } catch (e) {
    print(e);
  }
}

// 一种可能的结果:
// bar: after file.exists() returned
// foo: file not exists
// foo: after file.exists() returned
// bar: file not exists

这里的关键在于,bar 函数里面,file.exists() 执行完后,会马上执行下面的语句;而 foo 则会等待结果,然后才继续执行。关于 Future 的更多的细节,强烈建议读者阅读https://webdev.dartlang.org/articles/performance/event-loop。

最后需要说明的是,Dart 的生成器、Stream 在这里我们并没有介绍,读者可以参考 https://www.dartlang.org/guides/language/language-tour。此外,Dart 官网还有许多资源等待读者去发掘。

2018/12/11 posted in  Flutter

如何计算文字长度

Text t = Text("hello world");
TextPainter textPainter = TextPainter(
   textDirection: TextDirection.ltr,
   text: t.textSpan,
).layout();
double width = textPainter.width;
2018/08/13 posted in  Flutter

Flutter 开源组件收藏

2018/08/08 posted in  Flutter

Golang 在 Mac、Linux、Windows 下如何交叉编译

Golang 支持交叉编译,在一个平台上生成另一个平台的可执行程序,最近使用了一下,非常好用,这里备忘一下。

Mac 下编译 Linux 和 Windows 64位可执行程序

CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build main.go
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build main.go

Linux 下编译 Mac 和 Windows 64位可执行程序

CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build main.go
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build main.go

Windows 下编译 Mac 和 Linux 64位可执行程序

SET CGO_ENABLED=0
SET GOOS=darwin
SET GOARCH=amd64
go build main.go

SET CGO_ENABLED=0
SET GOOS=linux
SET GOARCH=amd64
go build main.go

GOOS:目标平台的操作系统(darwin、freebsd、linux、windows)
GOARCH:目标平台的体系架构(386、amd64、arm)
交叉编译不支持 CGO 所以要禁用它

上面的命令编译 64 位可执行程序,你当然应该也会使用 386 编译 32 位可执行程序
很多博客都提到要先增加对其它平台的支持,但是我跳过那一步,上面所列的命令也都能成功,且得到我想要的结果,可见那一步应该是非必须的,或是我所使用的 Go 版本已默认支持所有平台。

2018/07/24 posted in  Golang

Flutter 布局学习

容器

flutter 中的 Container Widget 类似于 HTML 中的 DIV

var container = new Container( // grey box
  child: new Text(
    "Lorem ipsum",
    style: new TextStyle(
      fontSize: 24.0
      fontWeight: FontWeight.w900,
      fontFamily: "Georgia",
    ),
  ),
  width: 320.0,
  height: 240.0,
  color: Colors.grey[300],
);

样式

设置样式使用 TextStyle Widget 中,有一个style的属性,在这里可以设置样式。

TextStyle bold24Roboto = new TextStyle(
  color: Colors.white,
  fontSize: 24.0,
  fontWeight: FontWeight.w900,
);

居中组件

在 flutter 中组件要居中使用 Center widget

var container = new Container( // grey box
  child:  new Center(
    child:  new Text(
      "Lorem ipsum",
      style: bold24Roboto,
    ),
  ),
  width: 320.0,
  height: 240.0,
  color: Colors.grey[300],
);

设置容器宽度

要指定Container的宽度,请设置其width属性。 这是一个固定的宽度,不像CSS中max-width属性,它可以设置容器宽度最大值。要在Flutter中模拟这种效果,请使用容器的constraints属性。 创建一个新的BoxConstraints来设置minWidth或maxWidth。

对于嵌套容器,如果父级的宽度小于子级宽度,则子级容器将自行调整大小以匹配父级。

var container = new Container( // grey box
  child: new Center(
    child: new Container( // red box
      child: new Text(
        "Lorem ipsum",
        style: bold24Roboto,
      ),
      decoration: new BoxDecoration(
        color: Colors.red[400],
      ),
      padding: new EdgeInsets.all(16.0),
      width: 240.0, //max-width is 240.0
    ),
  ),
  width: 320.0, 
  height: 240.0,
  color: Colors.grey[300],
);

控制位置和大小

更深度可以控制 widget 位置、大小和背景上执行更复杂的操作。

设置绝对位置

默认情况下,widget 相对于其父 widget 定位。

要将 widget 的绝对位置指定为x-y坐标,请将其嵌套在 Positioned Widget 中, 该 widget 又嵌套在 Stack widget 中。

var container = new Container( // grey box
  child: new Stack(
    children: [
      new Positioned( // red box
        child:  new Container(
          child: new Text(
            "Lorem ipsum",
            style: bold24Roboto,
          ),
          decoration: new BoxDecoration(
            color: Colors.red[400],
          ),
          padding: new EdgeInsets.all(16.0),
        ),
        left: 24.0,
        top: 24.0,
      ),
    ],
  ), 
  width: 320.0,
  height: 240.0,
  color: Colors.grey[300],
);

处理形状

圆角

要给矩形添加圆角请使用BoxDecoration对象的borderRadius属性 。 创建一个新的BorderRadius对象,给该对象指定一个的半径(会四舍五入)。

var container = new Container( // grey box
  child: new Center(
    child: new Container( // red circle
      child: new Text(
        "Lorem ipsum",
        style: bold24Roboto,
      ),
      decoration: new BoxDecoration(
        color: Colors.red[400],
        borderRadius: new BorderRadius.all(
          const Radius.circular(8.0),
        ), 
      ),
      padding: new EdgeInsets.all(16.0),
    ),
  ),
  width: 320.0,
  height: 240.0,
  color: Colors.grey[300],
);

添加阴影

在CSS中,您可以使用box-shadow属性来快速指定阴影偏移和模糊。

在Flutter中,每个属性和值都单独指定。使用BoxDecoration的boxShadow属性创建BoxShadow列表。 您可以定义一个或多个BoxShadow,它们可以叠加出自定义阴影深度、颜色等。

var container = new Container( // grey box
  child: new Center(
    child: new Container( // red box
      child: new Text(
        "Lorem ipsum",
        style: bold24Roboto,
      ),
      decoration: new BoxDecoration(
        color: Colors.red[400],
        boxShadow: <BoxShadow>[
          new BoxShadow (
            color: const Color(0xcc000000),
            offset: new Offset(0.0, 2.0),
            blurRadius: 4.0,
          ),
          new BoxShadow (
            color: const Color(0x80000000),
            offset: new Offset(0.0, 6.0),
            blurRadius: 20.0,
          ),
        ], 
      ),
      padding: new EdgeInsets.all(16.0),
    ),
  ),
  width: 320.0,
  height: 240.0,
  decoration: new BoxDecoration(
    color: Colors.grey[300],
  ),
  margin: new EdgeInsets.only(bottom: 16.0),
);

圆和椭圆

在CSS中制作一个圆需要将矩形的四条边的border-radius设置为50%。

虽然BoxDecoration的borderRadius属性支持此方法, 但Flutter为此提供了一个shape属性, 值为BoxShape枚举 。

var container = new Container( // grey box
  child: new Center(
    child: new Container( // red circle
      child: new Text(
        "Lorem ipsum",
        style: bold24Roboto,
        textAlign: TextAlign.center, 
      ),
      decoration: new BoxDecoration(
        color: Colors.red[400],
        shape: BoxShape.circle, 
      ),
      padding: new EdgeInsets.all(16.0),
      width: 160.0,
      height: 160.0, 
    ),
  ),
  width: 320.0,
  height: 240.0,
  color: Colors.grey[300],
);

操作文本

调整文本间距

在CSS中,通过分别给出letter-spacing和word-spacing属性的长度值,指定每个字母或单词之间的空白间距。长度单位可以是px,pt,cm,em等。

在Flutter中,您将空白区域指定为Text的TextStyle的letterSpacing和wordSpacing属性, 值为逻辑像素(允许为负值)

var container = new Container( // grey box
  child: new Center(
    child: new Container( // red box
      child: new Text(
        "Lorem ipsum",
        style: new TextStyle(
          color: Colors.white,
          fontSize: 24.0,
          fontWeight: FontWeight.w900,
          letterSpacing: 4.0, 
        ),
      ),
      decoration: new BoxDecoration(
        color: Colors.red[400],
      ),
      padding: new EdgeInsets.all(16.0),
    ),
  ),
  width: 320.0,
  height: 240.0,
  color: Colors.grey[300],
);

转换文本

在HTML / CSS中,您可以使用text-transform属性执行简单大小写转换

在Flutter中,使用 dart:core库中的String 类的方法来转换Text的内容。

var container = new Container( // grey box
  child: new Center(
    child: new Container( // red box
      child: new Text(
        "Lorem ipsum".toUpperCase(), 
        style: bold24Roboto,
      ),
      decoration: new BoxDecoration(
        color: Colors.red[400],
      ),
      padding: new EdgeInsets.all(16.0),
    ),
  ),
  width: 320.0,
  height: 240.0,
  color: Colors.grey[300],
);

进行内联格式更改

Text widget控件,可以用相同的格式显示文本。 要显示使用多个样式的文本(在本例中为带有重点的单个单词),请改用RichText。 它的text属性可以指定一个或多个可单独设置样式的 TextSpanwidget

在以下示例中,“Lorem” 位于具有默认(继承)文本样式的 TextSpan 小部件中,“ipsum” 位于具有自定义样式的单独TextSpan中。

var container = new Container( // grey box
  child: new Center(
    child: new Container( // red box
      child:  new RichText(
        text: new TextSpan(
          style: bold24Roboto,
          children: <TextSpan>[
            new TextSpan(text: "Lorem "),
            new TextSpan(
              text: "ipsum",
              style: new TextStyle(
                fontWeight: FontWeight.w300,
                fontStyle: FontStyle.italic,
                fontSize: 48.0,
              ),
            ),
          ],
        ),
      ), 
      decoration: new BoxDecoration(
        backgroundColor: Colors.red[400],
      ),
      padding: new EdgeInsets.all(16.0),
    ),
  ),
  width: 320.0,
  height: 240.0,
  color: Colors.grey[300],
);

创建文本摘要

摘录显示段落中文本的最初行,并且通常使用省略号处理溢出文本。在HTML / CSS中,摘要不能超过一行。截断多行需要一些JavaScript代码。

在Flutter中,使用Text小部件的 maxLines 属性来指定要包含在摘要中的行数,以及用于处理溢出文本的属性 overflow

var container = new Container( // grey box
  child: new Center(
    child: new Container( // red box
      child: new Text(
        "Lorem ipsum dolor sit amet, consec etur",
        style: bold24Roboto,
        overflow: TextOverflow.ellipsis,
        maxLines: 1, 
      ),
      decoration: new BoxDecoration(
        backgroundColor: Colors.red[400],
      ),
      padding: new EdgeInsets.all(16.0),
    ),
  ),
  width: 320.0,
  height: 240.0,
  color: Colors.grey[300],
);
2018/07/22 posted in  Flutter

开源库

UUID生成 : https://github.com/dreamans/guuid
Golang动态口令库:https://github.com/xlzd/gotp
复杂JSON参数解析库: https://github.com/bitly/go-simplejson
时间解析库carbon:https://github.com/golang-module/carbon

仓库资源

如果在 go get 或者 glide get 的时候提示以下错误:

[WARN] Unable to checkout golang.org/x/crypto
[ERROR] Update failed for golang.org/x/crypto: Cannot detect VCS
[WARN] Unable to checkout golang.org/x/net
[ERROR] Update failed for golang.org/x/net: Cannot detect VCS
[ERROR] Failed to install: Cannot detect VCS
Cannot detect VCS

解决方法是设置golang.org镜像到github.com/golang

glide mirror set https://golang.org/x/mobile https://github.com/golang/mobile --vcs git
glide mirror set https://golang.org/x/crypto https://github.com/golang/crypto --vcs git
glide mirror set https://golang.org/x/net https://github.com/golang/net --vcs git
glide mirror set https://golang.org/x/tools https://github.com/golang/tools --vcs git
glide mirror set https://golang.org/x/text https://github.com/golang/text --vcs git
glide mirror set https://golang.org/x/image https://github.com/golang/image --vcs git
glide mirror set https://golang.org/x/sys https://github.com/golang/sys --vcs git
glide mirror set https://golang.org/x/net/websocket https://github.com/gorilla/websocket --vcs git
2018/03/22 posted in  Golang

在golang中使用mgo多条件查询

今天被mgo凶残的语法折腾跪了

一般做简单查询,是这样写的:

collection := mgodbcontroller.GetMdb().C(mgodbcontroller.USER_WALLET_GS_LOG)//获取操作对象
//根据用户手机号 倒序查询前100个 存入slice中
if err := collection.Find(&bson.M{"uphone": phonenum}).Sort("-initimesamp").Limit(100).All(&historys); err == nil {

	for i, _ := range historys {
		fmt.Println("从mgo查询到的数据--->", historys[i])
		ms = append(ms, &historys[i])
	}

} else {
	fmt.Println("查询历史", err)
	logUtils.GetLog().Error("查询历史", err)
}

现在需要查询这些用户中,手机号为18112345678,同时历史信息是reasonareasonb的历史,如果直接用命令来查询,那简单的很,这样写就好:

db.userwalletgslog.find({"uphone":"18112345678","reason":{"$in":["reasona","reasonb"]}})

接下来,苦逼的问题来了,要用golang调用mgo来实现上面这个语句,咋整
百度N久,找到个这么写的:(链接是 http://blog.csdn.net/varding/article/details/17200299 )

c.Find(bson.M{"name": bson.M{"$in": []string{"Jimmy Kuu", "Tracy Yu"}}}).All(&users)

他的这个写法其实有点问题,至少我的程序里跑不起来,经过了长~~~~~~时间的测试:

答案在此:

err := collection.Find(&bson.M{"uphone": "18112345678", "reason": &bson.M{"$in": []string{"reasona", "reasonb"}}}).All(&historys)

看到了嘛,看到了嘛,这个坑爹的&bson.M 我真心TMD啊

2017/08/24 posted in  Golang