【问题标题】:How to call and get result of void function?如何调用并获取 void 函数的结果?
【发布时间】:2020-06-26 08:29:42
【问题描述】:

说明:
在我的主页上,每个用户输入他们的昵称并单击按钮开始游戏。然后每个玩家必须回答多项选择,最后显示分数。

问题 当我调用“initQuestion()”时,我无法获取结果的值,并且出现一些错误,例如“此表达式的类型为 'void',无法使用。”或“方法驱动被调用为空”

代码 我的主页调用 Game() 函数:

import 'package:flutter/material.dart';
import 'package:trivia/src/screens/questionpage.dart';

class Game extends StatelessWidget {

  final List<String> _playerNameList;
  final String gameMode; // Easy, Normal, Hard defined on HomePage
  Game(this.gameMode, this._playerNameList);


  Widget build(BuildContext context) {
    //variables
    int round = 3;
    int playerNumber = _playerNameList.length;
    Map<String, int> score; //List to store score like {'PlayerName1': '0', 'PlayerName2": '0', ...};

    //Function
    for (int i = 0; i < round; i++) { //for each round
      for (int j = 0; j < playerNumber; j++) { //for each player

        int result = initQuestion(context, gameMode, _playerNameList[j]); // Run "Question game"
        score[_playerNameList[j]] = score[_playerNameList[j]]+result; // Get result (1 if answer correct; 0 if answer invalid) and store score

      }
    }

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Game end'),
        ),
        body: Center(
          child: Text('The winner is ...'),
        ),
      ),
    );
  }
}

initQuestion(context, gameMode, playerName) async {

    //Question
    String question = "In which continent is France located?";
    List<String> _choice = <String>["Europe","Asia","Africa"];
    String answer = "Europe";

  final result = await Navigator.push(context, MaterialPageRoute(builder: (context) => QuestionPage(playerName: playerName, answer: answer, choice: _choice, question: question)),
  );
  //Get result (0 or 1)
  return result; //--> Edited thx Selim Kundakçıoğlu

}

【问题讨论】:

    标签: android flutter dart


    【解决方案1】:

    void 表示函数不返回任何内容。因此,您可以将返回类型更改为int,而不是使用void,而不是print(result);,您可以使用return result;

    【讨论】:

    • 谢谢我编辑了我的代码,我还有其他错误消息“NoSuchMethodError:方法'驱动'被调用为空'。我不知道它可能来自哪里
    • 你有一个叫驱动的方法吗?
    • 我没有“驱动”方法。我的控制台中的根错误消息是:类型“Future”不是“int”类型的子类型。我认为问题来自“分数”列表
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-28
    • 2013-05-06
    • 2016-04-22
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    相关资源
    最近更新 更多