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.
4
Answers
Do it like this with ternary operator
Using If statements inside the UI page is Not recommended,
You Can Do What you want in tow way:
1- Using Visibility Widget, to Hide One Widget and show another one.
2- You Can Use Ternary if statement Like this:
And as I say, using a lot of code inside UI page is note recommended.
Don’t be shy to ask me any thing if any.
You are creating a Set using the curly braces to read more about SET visit set literal. Your build function should be like this,
Or you can use the ternary operator, Example code
{} is making it a Set so you can access its Data like here to {}.first gets first object/value from set,
in your case it is treated as a set with undefined number Objects
.
or, you can also use the spread operator (…) for widgets that require the same if condition