Flutter随笔02

194 阅读2分钟
1. 关于在Row中使用Expand需要注意点

以前我以为Expand总是在Row中是可以使用的,其实实际不是这样的,只有在Row是有约束宽度的时候才可以使用,当Rowwrap_content的时候,是没有效果的,编辑器也会报错。

2. Flutter中的Function

在Dart语言中,Function是一个特殊的类型,它代表了任何函数类型的超类。所有的函数类型都可以赋值给Function类型的变量。

// 定义一个具有具体签名的函数
void printHello() {
    print("Hello");
}

// 将一个具有具体签名的函数赋值给Function类型的变量
Function helloFunction = printHello;

// 调用这个函数
helloFunction(); // 输出: Hello


// 定义一个接受任意数量参数的函数
Function anyFunction = (dynamic arg1, [dynamic arg2]) {
   print("arg1: $arg1");
   if (arg2 != null) {
       print("arg2: $arg2");
   }
};


// 调用这个函数
anyFunction(42);  // 输出: arg1: 42
anyFunction(42, "hello");  // 输出: arg1: 42, arg2: hello
3. GestureDetector嵌套Row,Row又嵌套Expand遇到的问题
GestureDetector(
  onTap: onClick,
  child: Container(
    height: 60,
    padding: const EdgeInsets.symmetric(vertical: 0, horizontal: 16),
    child: Row(
      children: [
        Text(
          title,
          style: const TextStyle(
              fontSize: 12,
              color: Colors.black,
              fontWeight: FontWeight.bold
          ),
        ),
        Expanded(flex: 1, child: Container(height: 60, color: Colors.black)),
        const Icon(Icons.arrow_forward_ios, size: 18)
      ],
    ),
  ),
)

当点击中间的Expanded区域没有响应的时候,我们可以将里面的Container设置高度和背景。 还有一种方式是使用InkWell替换GestureDetector

4. ?? 空合并运算符
  • ?? 叫空合并运算符,它用于在左侧表达式的结果为null的时候,将右侧的表达式作为结果,否则就返回左侧 表达式的值。

  • 这个运算符通常用于提供默认值,以避免在变量可能为null时,出现空安全错误。

var result = a ?? b;
  • 当a为null的时候,返回b
  • 当a不为null的时候,返回a