Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter 如何在小部件树中添加命令?_Flutter_Dart - Fatal编程技术网

Flutter 如何在小部件树中添加命令?

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

在flatter/dart中,如何在小部件树中添加命令(用于循环、if/then等)

假设我们有一棵树

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
之类的控制结构实际上没有任何意义