我能不能在 List 中的 if 语句里写花括号?
我能不能在 List 中的 if 语句里写花括号?
以下未添加大括号的代码运行良好:
import 'package:flutter/material.dart'; void main() { runApp(const _MyApp()); } class _MyApp extends StatelessWidget { const _MyApp({super.key}); @override Widget build(BuildContext context) { const isFlag = true; return MaterialApp( home: Scaffold( body: Column( children: const [ Text( "Demo1", ), if (isFlag) Text( "Demo true", ) else Text( "Demo flase", ) ], ), ), ); } }
即使只有一个表达式,我也更喜欢添加大括号。
我做了以下尝试,但导致错误。
导致错误的代码:
import 'package:flutter/material.dart'; void main() { runApp(const _MyApp()); } class _MyApp extends StatelessWidget { const _MyApp({super.key}); @override Widget build(BuildContext context) { const isFlag = true; return MaterialApp( home: Scaffold( body: Column( children: const [ Text( "Demo1", ), if (isFlag) { Text( "Demo true", ) } else { Text( "Demo flase", ) } ], ), ), ); } }
错误:
lib/main.dart:21:25: Error: A value of type 'Set' can't be assigned to a variable of type 'Widget'. - 'Set' is from 'dart:core'. - 'Text' is from 'package:flutter/src/widgets/text.dart' ('../../../flutter-command/flutter/packages/flutter/lib/src/widgets/text.dart'). - 'Widget' is from 'package:flutter/src/widgets/framework.dart' ('../../../flutter-command/flutter/packages/flutter/lib/src/widgets/framework.dart'). if (isFlag) { ^ lib/main.dart:25:20: Error: A value of type 'Set' can't be assigned to a variable of type 'Widget'. - 'Set' is from 'dart:core'. - 'Text' is from 'package:flutter/src/widgets/text.dart' ('../../../flutter-command/flutter/packages/flutter/lib/src/widgets/text.dart'). - 'Widget' is from 'package:flutter/src/widgets/framework.dart' ('../../../flutter-command/flutter/packages/flutter/lib/src/widgets/framework.dart'). } else {
我是否不能在List的if语句中编写大括号?
参考以下链接:
如何在Flutter Widget(居中Widget)的子属性中使用条件语句
附言:
问题只关于是否可以应用大括号。
我之所以提出这个问题,是因为我对Dart语法感兴趣。
admin 更改状态以发布 2023年5月22日
你正在使用花括号创建一个集合(Set),想要了解更多关于集合的信息请访问集合。你的构建函数应该像这样:
return MaterialApp( home: Scaffold( body: Column( children: const [ Text( "Demo1", ), if (isFlag) Text( "Demo true", ) else Text( "Demo flase", ) ], ), ), );
或者你可以使用三目运算符,例如代码:
return MaterialApp( home: Scaffold( body: Column( children: const [ Text( "Demo1", ), isFlag ? Text("Demo true",) : Text("Demo flase") ], ), ), );