【问题标题】:Getting a Mapping error when trying to Retrieve a list of strings尝试检索字符串列表时出现映射错误
【发布时间】:2022-01-20 04:29:25
【问题描述】:

我目前正在关注一个有点像飞镖速成课程的 YouTube 视频,所以请原谅我在这里可能缺乏知识。我试图使用映射来创建一个带有自己的答案集的问题小部件,在用户点击时更改为带有新答案的新问题。这是我的 Main 类、答案小部件的类和问题小部件的代码。我的问题出现在我的主要课程的第 49 行 (问题[_questionIndex] ['questionText']),我收到一条错误消息“参数类型'对象?'无法分配给参数类型“字符串”。似乎找不到解决方案,任何帮助将不胜感激。

主要:

void answerQuestions() {
  setState(() {
    _questionIndex = _questionIndex + 1;
  });
  print(_questionIndex);
}

var questions = [
  {
    'questionText': 'what is your favorite color',
    'answers': ['black', 'red', 'green' 'white'],
  },
  {
    'questionText': 'what is your favorite animal',
    'answers': ['Giraffe' 'Lion', 'Snake', 'Gorilla'],
  },
  {
    'questionText': 'what is your favorite brand',
    'answers': ['Polo' 'BBC', 'YSL', 'Jordan'],
  },
];
return MaterialApp(
    home: Scaffold(
        appBar: AppBar(
          title: Text('My First App'),
        ),
        body: Column(
          children: [
            Question(
              questions[_questionIndex]['questionText'],
            ),
            answer(answerQuestions),
            answer(answerQuestions),
            answer(answerQuestions),
          ],
        )));

}

答案:

class answer extends StatelessWidget {
  final VoidCallback selectHandler;

  answer(this.selectHandler);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      color: Colors.blue,
      child: ElevatedButton(
        child: Text('Answer1'),
        onPressed: selectHandler,
        style: ElevatedButton.styleFrom(
          onPrimary: Colors.white,
        ),
      ),
    );
  }
}

问题:

class Question extends StatelessWidget {
  late final String questionText;

  Question(this.questionText);

  @override
  Widget build(BuildContext context) {
    return Container(
        width: double.infinity,
        margin: EdgeInsets.all(10),
        child: Text(
          questionText,
          style: TextStyle(fontSize: 28),
          textAlign: TextAlign.center,
        ));
  }
}

【问题讨论】:

    标签: firebase flutter dart


    【解决方案1】:

    这就是你的questions 变量看起来像飞镖:

    [
      {
        'some string': <SOMETHING>
        ...
      }
      ...
    ]
    

    所以基本上它是一个映射列表,每个映射都有一个 string 键和其他值作为值。因此,当您阅读questions[_questionIndex]['questionText'] 时,作为开发人员您知道questionText 是一个字符串,但dart 不知道它可能是什么。要告诉 dart 它是一个字符串,可以使用 as 关键字:

    Question(
      questions[_questionIndex]['questionText'] as String,
    ),
    

    【讨论】:

    • 效果很好,谢谢!也感谢您的解释。
    猜你喜欢
    • 1970-01-01
    • 2019-11-20
    • 1970-01-01
    • 1970-01-01
    • 2022-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多