扑 "this function has a return type of void and cannot be used"

Flutter "this function has a return type of void and cannot be used"

我收到这个错误:- 此表达式的类型为 'void',因此无法使用其值。 尝试检查您是否使用了正确的 API;可能有一个函数或调用 returns void 您没有想到。还要检查也可能为空的类型参数和变量。

在此代码的第 134 行:-


class toDoList extends StatefulWidget
{
    bool data = false;
    @override
    createState() 
    {
        return new toDoListState();
    }
}

class toDoListState extends State<toDoList>
{
  List<String> tasks = [];
  List<String> completedTasks = [];
  List<String> descriptions = [];
  List<bool> importance = [];
  
    @override
    Widget build(BuildContext context)
    {
        return Scaffold
        (
            body: buildToDoList(),
            floatingActionButton: new FloatingActionButton
            (
                onPressed: addToDoItemScreen, 
                tooltip: 'Add Task',
                child: new Icon(Icons.add),
            ),
        );
    }

    Widget buildToDoList()
    {
        return new ListView.builder
        (
            itemBuilder: (context, index)
            {
                if(index < tasks.length)
                {
                    return row(tasks[index], descriptions[index], index);
                }
            },
        );
    }

    Widget row(String task, String description, int index)
    {                  
        return Dismissible(
        key: UniqueKey(),
        background: Container(color: Colors.red, child: Align(alignment: Alignment.center, child: Text('DELETE', textAlign: TextAlign.center, style: TextStyle(color: Colors.white, fontSize: 18),))),
        direction: DismissDirection.horizontal,
        onDismissed: (direction) {
        setState(() {
          tasks.removeAt(index);
          if(completedTasks.contains(task))
          {
              completedTasks.removeAt(index);
          }
          descriptions.removeAt(index);
          importance.removeAt(index);
        });
          Scaffold.of(context).showSnackBar(SnackBar(content: Text(task+" dismissed")));
        },
        child: CheckboxListTile(
          controlAffinity: ListTileControlAffinity.leading,
          title: Text(task, style: (completedTasks.contains(task)) ? TextStyle(decoration: TextDecoration.lineThrough) : TextStyle(),),
          subtitle: (importance[index]) ? Text('This is important') : Text('No it\'s not'),
          value: completedTasks.contains(task),
          onChanged: (bool value) {
           setState(() {
              if(!completedTasks.contains(task))
              {
                  completedTasks.add(task);
              }
              else
              {
                  completedTasks.remove(task);
              }
           });
          },
        ));
    }
  
  void addToDoItemScreen() {
    int index = tasks.length;
    while (importance.length > tasks.length) {
      importance.removeLast();
    }
    importance.add(false);
    Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
      return StatefulBuilder(builder: (context, setState) { // this is new
        return new Scaffold(
            appBar: new AppBar(title: new Text('Add a new task')),
            body: Form(
              child: Column(
                children: <Widget>[
                  TextField(
                    autofocus: true,
                    onSubmitted: (name) {
                      addToDoItem(name);
                      //Navigator.pop(context); // Close the add todo screen
                    },
                    decoration: new InputDecoration(
                        hintText: 'Enter something to do...',
                        contentPadding: const EdgeInsets.all(20.0),
                        border: OutlineInputBorder()),
                  ),
                  TextField(
                    //autofocus: true,
                    onSubmitted: (val) {
                      addDescription(val, index);
                    },
                    decoration: new InputDecoration(
                        hintText: 'Enter a task decription...',
                        contentPadding: const EdgeInsets.all(20.0),
                        border: OutlineInputBorder()),
                  ),
                  Row(
                    children: <Widget> [
                      Switch(
                      value: importance[index],
                      onChanged: (val) {
                        setState(() {
                        });
                        impTask(index);
                      },
                    ),
                    Text('Important Task', style: TextStyle(fontSize: 18)),
                    ],
                  ),
                  RaisedButton(onPressed: Navigator.pop(context),)
                ],
              ),
            ));
      });
    }));
  }

    void addToDoItem(String task)
    {
        setState(() {
          tasks.add(task);
          descriptions.add("No description");
        });
    }

    void addDescription(String desc, int index)
    {
        setState(() {
          descriptions[index] = desc;
        });
    }

    void impTask(int index)
    {
        setState(() {
          if(importance[index])
          {
            importance[index] = false;
          }
          else 
          {
            importance[index] = true;
          }
        });
    }
}

我不明白这是什么。我是新手。这是我的第一个应用程序。有人可以帮我解决这个问题吗?

问题出在您的 RaisedButton onPressed 上。

onPressed 属性 是一个 VoidCallback,它包含一个 Function

改成下面的代码:

RaisedButton(onPressed: () => Navigator.pop(context),)

如果你想调用一个函数,试试这个:

floatingActionButton: new FloatingActionButton
        (
            onPressed: () { addToDoItemScreen(); }, 
            
        ),

你的函数是这样的:

void addToDoItemScreen() {
   //body
}

如果您想导航到不同的屏幕,则必须将上下文作为参数传递:

floatingActionButton: new FloatingActionButton
    (
        onPressed: () { addToDoItemScreen(context); }, 

    ),

和功能:

void addToDoItemScreen(BuildContext context)) {
//body
}

受上面 Void 回答的启发,我只是将代码提取到一个函数中,它具有相同的行为,但我认为它更有条理,因为您可以重用代码:)

回答:

  _back(BuildContext context) {
    Navigator.pop(context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 2.0,
        leading: IconButton(
          key: const ValueKey('back'),
          icon: const Icon(Icons.arrow_back),
          onPressed: () => _back(context),
        ),
        title: const Text('Foo Title'),
      ),
      body: _buildBody(context),
    );
  }

将“onPressed: addToDoItemScreen”改为“onPressed: ()=>addToDoItemScreen