小部件中的if语句颤动 [英] Flutter if statement within widget

查看:76
本文介绍了小部件中的if语句颤动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不确定为什么该if语句不起作用:

Not sure why this if statement is not working:

  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          if (text.length > 0) {
             for (var val in text) Center(child: etc..)
            }
        ],
      ),
)

如果没有if语句,if语句(现在已删除)中的代码可以正常工作,但是一旦添加它,我就会收到错误无法分配元素类型 Map到列表类型'Widget'

The code within the if statement (removed for now) works fine without the if statement, but as soon as I add it I get the error The element type 'Map' can't be assigned to the list type 'Widget'.

我应该如何在窗口小部件中编写if语句?我意识到它在 return 语句之内,但不确定为什么for循环很好,但if语句却不行。.

How should I compose this if statement within a widget? I realise it's within a return statement but not sure why the for loop is fine but not the if statement..

推荐答案

for循环在集合内部很好,因为它是 Dart 的新功能(从2.3版开始)。例如,下一个代码片段将生成新的正方形列表:

for loop is fine inside collection because it is new Dart feature (starting from version 2.3). For example next snippet generates new list of squares:

  var numbers = [1, 2, 3, 4, 5];
  var squares = [for (var n in numbers) n * n];
  print(squares); // [1, 4, 9, 16, 25]

if 内部集合也是Dart 2.3的新增功能,并且允许过滤器元素移出:

if inside collection also new for Dart 2.3 and allow filter elements out:

  bool includeZero = false;
  var all = [if (includeZero) 0, 1, 2, 3, 4, 5];
  print(all); // [1, 2, 3, 4, 5]

您甚至可以结合使用以下两种构造:

You can even combine both construction:

  var includeSquares = true;
  var allWithSquares = [
    ...numbers,
    if (includeSquares) for (var n in numbers) n * n
  ];
  print(allWithSquares); // [1, 2, 3, 4, 5, 1, 4, 9, 16, 25]

您唯一不能做的就是使用花括号作为集合内的代码块。
您仍然可以使用花括号将Map定义为元素。在您的情况下,花括号给出了下一个结果:

The only thing you can't do is use curly braces as code blocks inside collections. You still can use curly braces to define Map as element. In your case curly braces gives next result:

  var includeSquares = true;
  var allWithSquares = [
    ...numbers,
    if (includeSquares) {for (var n in numbers) n * n}
  ];
  print(allWithSquares); // [1, 2, 3, 4, 5, {1, 4, 9, 16, 25}]

您可以在此处了解更多信息

这篇关于小部件中的if语句颤动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆