Условный рендеринг во Flutter

У класса Task поле description опциональное:

class Task {

  String title;
  String? description;
  bool isDone;

  // ...
}

Как отрендерить виджет Text с этим описанием только в том случае, когда поле description определено?

class TaskCard extends StatelessWidget {

  final Task task;

  TaskCard({
    Key? key,
    required this.task
  }) : super(key: key);


  @override
  Widget build(BuildContext context) {
    return (
      Container(
        decoration: BoxDecoration(/* ... */),
        child: Row(
          children: [
            Checkbox(value: this.task.isDone, onChanged: this.onClickCheckBox),
            Expanded(child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  this.task.title,
                  style: TextStyle(
                    fontSize: 18.0,
                    fontWeight: FontWeight.w700
                  )
                ),
                Text(
                  this.task.description,
                  style: TextStyle(
                    fontSize: 18.0,
                    fontWeight: FontWeight.w700
                  )
                )
              ]
            ))
          ]
        )
      )
    );
  }

  // ...
}

На данный момент будет ошибка

The argument type 'String?' can't be assigned to the parameter type 'String'. 

Ответы (1 шт):

Автор решения: MiT

Так:

class TaskCard extends StatelessWidget {
  final Task task;

  const TaskCard({Key? key, required this.task}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final String? description = task.description; // создаём новую переменную

    return Container(
      decoration: BoxDecoration(/* ... */),
      child: Row(
        children: [
          Checkbox(value: task.isDone, onChanged: onClickCheckBox),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  task.title,
                  style: TextStyle(
                    fontSize: 18.0,
                    fontWeight: FontWeight.w700,
                  ),
                ),
                if (description != null) // проверяем её на не null
                  Text(
                    description,
                    style: TextStyle(
                      fontSize: 18.0,
                      fontWeight: FontWeight.w700,
                    ),
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // ...
}
→ Ссылка