Flutter 如何在小部件树中添加命令?
在flatter/dart中,如何在小部件树中添加命令(用于循环、if/then等) 假设我们有一棵树Flutter 如何在小部件树中添加命令?,flutter,dart,Flutter,Dart,在flatter/dart中,如何在小部件树中添加命令(用于循环、if/then等) 假设我们有一棵树 Scaffold(...) 如何在其中添加命令语法。唯一可能的是三元运算符。(据我所知)您可以在build()中这样做: Widget build(context) { // use for loop or if else or anything you need return Scaffold(...); } void initState() { super.initSt
Scaffold(...)
如何在其中添加命令语法。唯一可能的是三元运算符。(据我所知)您可以在
build()
中这样做:
Widget build(context) {
// use for loop or if else or anything you need
return Scaffold(...);
}
void initState() {
super.initState();
// use for, if-else
}
更好的方法是创建一个专门的方法,如
void _doSomethingHere() {
// use for, if-else etc
}
并在按下按钮时使用此方法,如:
RaisedButton(onPressed: _doSomething)
如果要在
build()
之前执行某些操作,可以覆盖initState()
如下所示:
Widget build(context) {
// use for loop or if else or anything you need
return Scaffold(...);
}
void initState() {
super.initState();
// use for, if-else
}
如果您使用的是
StatefulWidget
,则可以在initState()中执行此操作。Else在build()
方法中执行此操作。在将UI创建为小部件(-tree)时,不能使用控制结构(if-Else)或循环(for、while、do-while)的主要原因是,Flitter试图理解您试图创建的UI
控制结构if
只接受一个代码块,并在给定的条件满足时执行它
if(condition)
{
//statment(s) to be executed
}
而三元运算符只是根据给定的条件替换特定的代码/值行
(condition)
?
value-or-code-to-replaced-if-the-condition-satifies
:
value-or-code-to-replaced-if-the-condition-does-not-satisfy;
由于我们只是返回UI,因此使用return
关键字将小部件树添加到构建函数中,添加if
之类的控制结构实际上没有任何意义