тернарный оператор в обратном порядке — ФЛАТТЕР

#flutter #flutter-layout

Вопрос:

   Widget _buildItems() {
    return id == 0
        ? Column(Text("PAGE 1"))
        : Center(
            Text("PAGE 2"),
          );
  }
 

Привет, выше-часть моего кода флаттера, и я продолжаю получать ошибку ниже. Не могли бы вы, пожалуйста, разобраться в этом? Похоже, мой синтаксис неверен, но я просто не могу точно определить, где я ошибаюсь.

Спасибо.

         ? Column(Text("PAGE 1"))

                ^

packages/flutter/lib/src/widgets/basic.dart:4930:3: Context: Found this candidate, but the arguments don't match.

  Column({

  ^^^^^^

/lib/components/challenge_menu.dart:32:17: Error: Too many positional arguments: 0 allowed, but 1 found.

Try removing the extra positional arguments.

        : Center(

                ^

packages/flutter/lib/src/widgets/basic.dart:1984:9: Context: Found this candidate, but the arguments don't match.

  const Center({ Key? key, double? widthFactor, double? heightFactor, Widget? child })

        ^^^^^^

/lib/components/challenge_menu.dart:30:12: Error: The getter 'id' isn't defined for the class '_ChallengeMenuState'.

 - '_ChallengeMenuState' is from 'package:osam2021/components/challenge_menu.dart' ('/lib/components/challenge_menu.dart').

Try correcting the name to the name of an existing getter, or defining a getter or field named 'id'.

    return id == 0

           ^^
 

Ответ №1:

У каждого столбца есть обязательное свойство, называемое дочерними. Вы должны использовать это, чтобы включить любые под-виджеты внутри столбца.

Ответ №2:

В каждом столбце есть список «Детей», в вашем случае вы напрямую используете текстовый виджет внутри столбца, вы должны использовать вот так:

   Column(
           children:[
                       Text("your text"),
                         .....
                         ]

          )
 

Ответ №3:

Класс столбцов

Виджет, который отображает его дочерние элементы в вертикальном массиве.

 Column(
  children: const <Widget>[
    Text('Deliver features faster'),
    Text('Craft beautiful UIs'),
    Expanded(
      child: FittedBox(
        fit: BoxFit.contain, // otherwise the logo will be tiny
        child: FlutterLogo(),
      ),
    ),
  ],
)
 

для получения более подробной информации

и

Центр класса

Виджет, который центрирует своего ребенка внутри себя.

 Center(
     child: Container()
),
 

Вы забыли использовать «ребенок» и «дети».

Используйте оба виджета вместе:

 class LoginPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: Column(
          children: <Widget>[
            Center(
              child: Text('Logo'),
            ),
          ],
        ),
      ),
    );
  }
}  
 

Ответ №4:

 Widget _buildItems() {
return( id == 0)
    ? Column(children : [Text("PAGE 1")])
    : Center(child : 
        Text("PAGE 2")
      );
  }
 

Я не знаю, что вы собираетесь с этим делать, но просто исправьте ошибку