[英]Pass method as parameter to a widget
我有一個自定義按鈕小部件:
class Button extends StatelessWidget {
final String text;
Button(this.text);
@override
Widget build(BuildContext context) {
return Container(
height: 50,
child: SizedBox(
width: double.infinity,
child: RaisedButton(
onPressed: () => {}, // Use the function from parent Widget
child: Padding(
padding: EdgeInsets.symmetric(vertical: 13),
child: Text(
text,
style: TextStyle(fontWeight: FontWeight.bold),
)),
color: COLOR_BLUE,
textColor: Colors.white,
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(25)),
),
),
);
}
}
然后在父小部件中,我想將一個onPressed
方法傳遞給這個按鈕小部件:
...
myMethod () => {
// do some stuff
}
...
Padding(
padding: EdgeInsets.only(bottom: 10),
child: Button("Log in", myMethod),
),
...
如何告訴按鈕小部件將myMethod
用於onPress
?
像這樣使用VoidCallback
類型。 檢查我對代碼的評論:
class Button extends StatelessWidget {
final String text;
final VoidCallback callback; // Notice the variable type
Button(this.text, this.callback);
@override
Widget build(BuildContext context) {
return Container(
height: 50,
child: SizedBox(
width: double.infinity,
child: RaisedButton(
onPressed: callback, // Simply put the function name here, DON'T use ()
child: Padding(
padding: EdgeInsets.symmetric(vertical: 13),
child: Text(
text,
style: TextStyle(fontWeight: FontWeight.bold),
)),
color: COLOR_BLUE,
textColor: Colors.white,
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(25)),
),
),
);
}
}
已經存在一些預定義的類型。
如果你想創建一個像這樣的參數:
onPressed: () { },
然后你可以像這樣在你的類中定義它:
class MyWidget extends StatelessWidget {
MyWidget({Key key, this.onPressed}) : super(key: key);
final VoidCallback onPressed;
// ...
}
typedef
在源代碼中定義如下:
typedef VoidCallback = void Function();
異步版本是AsyncCallback
。
typedef AsyncCallback = Future<void> Function();
如果你想創建一個像這樣的參數:
onPressed: (value) { },
然后你可以像這樣在你的類中定義它:
class MyWidget extends StatelessWidget {
MyWidget({Key key, this.onPressed}) : super(key: key);
final ValueSetter<String> onPressed;
// ...
}
typedef 在源代碼中定義如下:
typedef ValueSetter<T> = void Function(T value);
如果要指定僅在發生更改時調用該函數,請改用 ValueChanged。
typedef ValueChanged<T> = void Function(T value);
異步版本是AsyncValueSetter
。
typedef AsyncValueSetter<T> = Future<void> Function(T value);
如果你想創建一個像這樣的參數:
onPressed: () => value,
然后你可以像這樣在你的類中定義它:
class MyWidget extends StatelessWidget {
MyWidget({Key key, this.onPressed}) : super(key: key);
final ValueGetter<String> onPressed;
// ...
}
typedef 在源代碼中定義如下:
typedef ValueGetter<T> = T Function();
異步版本是AsyncValueGetter
。
typedef AsyncValueGetter<T> = Future<T> Function();
從上面的所有示例中可以看出,一切都只是Function
的typedef
。 所以很容易制作自己的。
假設你想做這樣的事情:
onEvent: (context, child) => value,
然后你可以像這樣制作typedef:
typedef MyEventCallback = int Function(BuildContext context, Widget widget);
並像這樣使用它:
class MyWidget extends StatelessWidget {
MyWidget({Key key, this.onEvent}) : super(key: key);
final MyEventCallback onEvent;
// ...
}
有關更多信息,請參閱文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.