【问题标题】:Ternary operator in Flutter to return List<Widget>Flutter 中的三元运算符返回 List<Widget>
【发布时间】:2021-01-15 17:48:35
【问题描述】:

我正在尝试根据 swapped 值返回包含 2 个小部件的列表。我试过了:

Container(child: Row(children: swapped? [a, b]: [b, a],),

其中abWidget

Widget a = ...
Widget b = ...

但我得到了

The operator '[]' isn't defined for the type 'bool'.

我做错了什么?

swappedbool

我也试过

children: swapped? List<Widget>([a, b]): List<Widget>([b, a])

得到了

The argument type 'List<Widget>' can't be assigned to the parameter type 'int'.

【问题讨论】:

  • 您好,我尝试了同样的方法,它对我有用,您的错误可能是分号,您使用的是 [b:a] 而不是逗号
  • @AzadPrajapat 已编辑,这是一个错误。还是有问题

标签: flutter dart


【解决方案1】:

我在Colors中使用三元运算符时也遇到过类似的问题,导致类似的错误,请问如何解决?

将您的三元条件用括号括起来,如下所示

Container(child: Row(children: (swapped? [a, b]: [b, a]),),)

真正的代名词是什么: 当您编写条件以检查是否已交换时,飞镖首先通过布尔值,但每个人甚至飞镖都知道那本书!= List 然后它会拒绝您的代码并因此导致错误。

结论:

尽可能在三元运算符中使用括号。

【讨论】:

    【解决方案2】:

    在 dartpad 上检查以下代码的工作情况

    import 'package:flutter/material.dart';
    
    final Color darkBlue = Color.fromARGB(255, 18, 32, 47);
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
     bool swapped =true;
        Widget a=Text("2");
        Widget b = Text("4");
    
        return MaterialApp(
          theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
          debugShowCheckedModeBanner: false,
          home: Scaffold(
            body: Container(
                      child: Row(
                        children: swapped? [a,b]: [b,a],
                      ), 
          ),
            )
        );
      }
    }
    
     
    

    【讨论】:

      【解决方案3】:

      没有为类型“bool”定义运算符“[]”。

      我似乎无法用 DartPad 重现您的问题,但听起来您在三元运算符和 Dart 新的 null 安全功能引入的 new null-aware subscript operator 之间遇到了歧义。

      我也试过

      children: swapped? List<Widget>([a, b]): List<Widget>([b, a])
      

      得到了

      The argument type 'List<Widget>' can't be assigned to the parameter type 'int'.
      

      您收到该错误是因为List&lt;Widget&gt;([a, b]) 没有按照您的想法执行。 Dart 不支持重载函数,因此您正在调用(现已弃用)List constructor that takes a single length argument 并尝试将 List 作为长度传递。

      What you actually want,我认为应该解决原来的歧义,是:

      children: swapped ? <Widget>[a, b]: <Widget>[b, a],
      

      (由于我无法重现您的问题,因此了解您正在使用的 Dart 版本以及您是否可以提供最低限度可重现的示例会很有用。)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-13
        • 2011-04-03
        • 1970-01-01
        • 1970-01-01
        • 2020-01-25
        • 2012-12-25
        • 1970-01-01
        • 2016-07-09
        相关资源
        最近更新 更多