1

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.

shingo.nakanishi
  • 2,045
  • 2
  • 21
  • 55
  • use ternary operator. – OMi Shah Dec 26 '22 at 05:34
  • if you notice carefully you closed the Text() then creating new widget which will be condition statement instead you can try ternary condition or write like Text(((){conditions}). Please do check your referral link again and scroll down for more solutions – Lucky Trail Dec 26 '22 at 05:35
  • Braces contain *statements*, but the collection-`if` construct must produce an *expression* (or an "element"). See [What all statements can be executed inside `List`s, like `[ if(true), for(;;) ]`](https://stackoverflow.com/q/72610905/). I strongly recommend reading [Bob Nystrom's article explaining collection-`for` and collection-`if`.](https://medium.com/dartlang/making-dart-a-better-language-for-ui-f1ccaf9f546c). – jamesdlin Dec 26 '22 at 05:42
  • Use ternary operators: `isFlag ? (return this widget if true) : (return this widget if false)` . i.e -> `isFlag?Text("Demo true"):Text("Demo flase")` – Delwinn Dec 26 '22 at 06:24

4 Answers4

2

Do it like this with ternary operator

isFlag?Text("Demo true"):Text("Demo flase")
        
Ridha Rezzag
  • 3,672
  • 1
  • 34
  • 39
2

You are creating a Set using the curly braces to read more about SET visit set literal. Your build function should be like this,

return MaterialApp(
   home: Scaffold(
     body: Column(
       children: const [
         Text(
           "Demo1",
         ),
         if (isFlag)
           Text(
             "Demo true",
           )
         else
           Text(
             "Demo flase",
           )
       ],
     ),
   ),
);

Or you can use the ternary operator, Example code

return MaterialApp(
   home: Scaffold(
     body: Column(
       children: const [
         Text(
           "Demo1",
         ),
         isFlag ? Text("Demo true",) : Text("Demo flase")
       ],
     ),
   ),
);
Ahmad Raza
  • 758
  • 7
  • 26
1

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.

    return MaterialApp(
  home: Scaffold(
    body: Column(
      children: const [
        Text(
          "Demo1",
        ),
        Visibility(
         visible : isFlag, 
         child: Text(
            "Demo true",
          ),
         )
         Visibility(
         visible : !(isFlag), 
         child: Text(
            "Demo false",
          ),
         )
      ],
    ),
  ),
);

2- You Can Use Ternary if statement Like this:

        return MaterialApp(
  home: Scaffold(
    body: Column(
      children: const [
        Text(
          "Demo1",
        ),
        isFlag ? Text("Demo true",) : Text("Demo false"), 
      ],
    ),
  ),
);

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.

1
   [ 
     if(kDebugMode){
         Text('Data')
        }.first,
   ]

{} 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 .

   [
     if (!kDebugMode) ...{
        Text('Data'),
        Text('data'),
        },
     ]

or, you can also use the spread operator (...) for widgets that require the same if condition

Jay
  • 206
  • 1
  • 5