【问题标题】:How to map list with widgets in flutter如何在颤动中使用小部件映射列表
【发布时间】:2021-08-04 21:47:19
【问题描述】:

我想要一个普通的问题类型的东西。 一旦第一个问题得到回答,它应该转到下一个问题。 但是当我使用 .map() 时,出现了一个错误,因为“类型‘Null’不是类型转换中‘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”类型的子类型。

【问题讨论】:

    标签: list flutter widget


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 2021-08-27
      • 1970-01-01
      • 2019-11-25
      • 1970-01-01
      • 1970-01-01
      • 2021-04-10
      相关资源
      最近更新 更多