【问题标题】:Expected an identifier in Flutter ToDo AppFlutter ToDo App 中需要一个标识符
【发布时间】:2021-06-10 21:25:59
【问题描述】:

我目前正在关注 Flutter 中的 ToDo-App 教程。使用“复选框”功能的代码(用于显示您是否已完成任务),我收到以下错误: 需要一个标识符。

这是代码:

import 'package:flutter/material.dart';

class Check extends StatelessWidget {
  final bool? isActive;
  const Check({Key? key, this.isActive}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    if (isActive ??){
      return Container(
        width: 30,
        height: 30,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: Colors.green,
        ),
        child: Icon(
          Icons.check,
          size: 20,
          color: Colors.white,
        ),
      );
    } else {
      return Container(
        width: 30,
        height: 30,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: Colors.white,
        ),
        child: Icon(Icons.check, size: 20, color: Colors.white),
      );
    }
  }
}

如果您能在这方面支持我,将不胜感激。我大多是 Flutter 的新手,并且到处搜索我能想到的如何解决这个问题,但找不到任何东西。

【问题讨论】:

    标签: flutter dart identifier


    【解决方案1】:

    您的第一个条件似乎缺少一个操作数

    Widget build(BuildContext context) {
        if (isActive ?? false) {   <<< 
          return Container(
          ...
    

    你可以查看这个nullable operators article

    【讨论】:

    • 试过了,它似乎工作。非常感谢!
    【解决方案2】:

    您缺少第 9 行的第二个表达式

    if (isActive ?? false)
    

    ??运算符表示如果 expr1 不为 null,则返回其值;否则,计算并返回 expr2 的值。

    expr1 ?? expr2
    

    【讨论】:

    • 我认为有必要通过检查将bool?变成不可为空的类型bool
    • 我尝试使用不带“?”的布尔值但这似乎不起作用。非常感谢您的解释??操作员! :)
    【解决方案3】:

    更好的方法是使isActive 不可为空并为其提供默认值false

    class Check extends StatelessWidget {
      final bool isActive;
    
      const Check({
        Key? key, 
        this.isActive = false,
      }) : super(key: key);
    
      // ....
    }
    
    Avoid Nullable values when possible.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-07
      • 2018-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多