Flutter实例解析

2020-05-25  本文已影响0人  虫yu
Point(num x, num y) {
    // There's a better way to do this, stay tuned.
    this.x = x;
    this.y = y;
 }

语法糖:

Point(this.x, this.y);

同理:

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
 
  final String title;

  @override
  // _MyHomePageState类是MyHomePage类对应的状态类
  _MyHomePageState createState() => _MyHomePageState();
}
MyHomePage({Key key, this.title}) : super(key: key);

前半句是一个语法糖:

MyHomePage({Key key, this.title})

原本应该类似包含:

MyHomePage({Key key, String title}) {
    this.title = title;
}

调用超类构造函数:

: super(key: key)

实际这个构造方法很长。

附注:

可选参数也分为两类:

// 声明和实现
bool say(String msg , {String from, int clock}){
    print(msg+" from " + from + " at " + clock.toString());
    return true;
}
// 调用
say('Hello Flutter',clock: 11);
say('Hello Flutter',from: 'XiaoMing',clock: 11);
// 声明和实现
bool say(String msg , [String from , int clock]){
    print(msg+" from " + from + " at " + clock.toString());
    return true;
}
// 调用
say('Hello Flutter','XiaoMing')//✅
say('Hello Flutter',1)//❌ 因为  1 赋值给了 from,但是 from 是String,所以会报错

推荐阅读:

【开发经验】Flutter避免代码嵌套,写好build方法

上一篇 下一篇

猜你喜欢

热点阅读