The following without braces worked fine:
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",
)
],
),
),
);
}
}
I prefer to add braces even if there is only one expression.
I did the following and it resulted in an error.
The code that causes an error:
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",
)
}
],
),
),
);
}
}
Error:
lib/main.dart:21:25: Error: A value of type 'Set<Text>' 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<Text>' 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 {
Can't I write braces in an if statement in List?
Referred to the following:
How to use conditional statement within child attribute of a Flutter Widget (Center Widget)
PS:
The question is only about whether or not braces can be applied.
I am asking this question because I am interested in Dart syntax.