如何使用颤振中的小部件映射列表

时间:2021-05-14 18:06:52

标签: list flutter widget

我想要一个正常的问题类型。 一旦第一个问题得到回答,它应该转到下一个问题。 但是有一个错误,因为当我使用 .map() 时,'type 'Null' 不是 type cast' 中类型 'List' 的子类型。 .map() 和 spread 运算符曾经在之前版本的 flutter 中起作用,但现在它们不起作用了。有人可以为此提供解决方案吗?

这是下面的代码-main.dart


class MyAppState extends State<MyApp> {
  int qindex = 0;

  void answeQues() {
    setState(() {
      qindex = qindex + 1;
    });

    print(qindex);
  }

  @override
  Widget build(BuildContext context) {
    var questions = [
      {
        'questionText': 'what\'s your favourite color?',
        'answers': ['R', 'G', 'B', 'Y']
      },
      {
        'questionText': 'what\'s your favourite animal?',
        ' answers': ['Rabbit', 'Giraffe', 'Bear', 'Yax']
      },
      {
        'questionText': 'what\'s your favourite sport?',
        'answers': ['Rugby', 'Cricket', 'Basketball', 'Football']
      },
    ];

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('My first App'),
        ),
        body: Column(
          children: [
            Questions(
              questions[qindex]['questionText'].toString(),
            ),
            ...(questions[qindex]['answers'] as List<String>).map((answer) {
              return Answers(answeQues, answer);
            }).toList()

            // questions[qindex]['answers'].entries.map((answer) {
            //   return Answers(answeQues, answer);
            // }).toList()
          ],
        ),
      ),
    );
  }
}

这是我的 answers.dart 文件

import 'package:flutter/material.dart';

class Answers extends StatelessWidget {
  final Function selectHandler;
  final String answerText;

  Answers(this.selectHandler, this.answerText);
  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(10),
      child: RaisedButton(
        color: Colors.blue,
        child: Text(answerText),
        onPressed: () {
          selectHandler();
        },
      ),
    );
  }
}

错误:-

'Null' 类型不是类型转换中类型 'List' 的子类型。

1 个答案:

答案 0 :(得分:1)

对于您的第二个问题,键名 (' answers') 的开头有空格,这会导致问题:

var questions = [
  ...
  {
    'questionText': 'what\'s your favourite animal?',
    ' answers': ['Rabbit', 'Giraffe', 'Bear', 'Yax']
  },
  ...
];

.map() 和扩展运算符没有错,它们仍然在 Flutter 中使用。