【问题标题】:Flutter: The element type 'String' can't be assigned to the list type 'Widget'Flutter:无法将元素类型“String”分配给列表类型“Widget”
【发布时间】:2021-12-16 15:11:25
【问题描述】:

首先,我真的很新

我不明白为什么会出现这两个错误: 1.元素类型'String'不能分配给列表类型'Widget'。 2.期望找到']'。

import 'package:flutter/material.dart';

import './qs.dart';
import 'answer.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  //override is basically useless
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _MyAppState();
  } //refers to the particular class
}

class _MyAppState extends State<MyApp> {
  //an underscore means that the particular class can only be called
  //within htat particular file
  var _questionindex = 0;
  @override
  void _answerQuestion() {
    setState(() {
      _questionindex = _questionindex + 1;
    });
    print(_questionindex);
  } //helps in reloading the state whenever the values of a vriable is updated

  @override
  Widget build(BuildContext context) {
    var questions = [
      {
        'questiontext':'What\s your Age group?',
      'answers':['No','No','No','No'],
      },
      {
        'questiontext':'What\s your profession?',
      'answers':['student','teacher','government official','[private enterprise']
      },
      {
        'questiontext':'At what time do you get up?',
      'answers':['4am-6am','6am-7am','7am-8am','After 8am']}
      ];

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text(
            'Dragons be here',
            style: TextStyle(
              fontFamily: "Arial",
              fontSize: 35,
              fontWeight: FontWeight.bold,
            ),
          ),
          titleSpacing: 1.0,
          centerTitle: true,
          shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(bottom: Radius.circular(30)),
          ),
        ),

        body: Column(
          children: <Widget>[
            qs(
              questions[_questionindex]['questiontext'] as String,
            ),
            ...(questions[_questionindex]['answers']) as List<String>.map((answer){
              Answer(_answerQuestion,answer);
            }).toList()
  
          ],
        ),
      ),
    );
  }


   }

import 'package:flutter/material.dart';

class qs extends StatelessWidget {
  final String questionStr;
  qs(this.questionStr);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      child: Text(
        questionStr,
      ),
    );
  }
}

import 'package:flutter/material.dart';

class Answer extends StatelessWidget {
  final VoidCallback ansk;
  //idk y but function is snot working, 
  //if it is not wrking use Voidcallback
  final String gimme_da_answer;

  Answer(this.ansk, this.gimme_da_answer);
  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      child: ElevatedButton(
        onPressed: ansk,
        child: Text(gimme_da_answer),
        style: ButtonStyle(
          backgroundColor: MaterialStateProperty.all<Color>(Colors.amberAccent),
          foregroundColor: MaterialStateProperty.all<Color>(Colors.blueAccent),
        ),
      ),
    );
  }
}

另外,我不完全了解 dart 中的地图是什么,如果有人给出简要概述,那将是真正的 halpful

如果你读到这里,谢谢

【问题讨论】:

  • 您在哪一行收到此错误?
  • @Diwyansh 第 73 行显示两个错误 ...(questions[_questionindex]['answers']) 作为 List.map((answer){ Answer(_answerQuestion,answer ); }).toList()

标签: flutter dart


【解决方案1】:
...(questions[_questionindex]['answers']) as List<String>.map((answer){
              Answer(_answerQuestion,answer);
            }).toList()

上述代码导致您出现问题的原因有两个。

  1. List&lt;String&gt;.map(... 令人困惑 dart,因为它认为您正在调用 List&lt;String&gt; 上的某些方法,要解决此问题,请用另一对括号括起来
...((questions[_questionindex]['answers']) as List<String>).map((answer){
              Answer(_answerQuestion,answer);
            }).toList()
  1. map 方法不返回任何内容,您很可能忘记添加 return 语句,要解决此问题,只需添加 return 语句:
...((questions[_questionindex]['answers']) as List<String>).map((answer){
              return Answer(_answerQuestion,answer);
            }).toList()

关于预计会找到']'。抱歉,在我的编辑器中复制并粘贴您的代码后,我没有收到此错误...您介意显示一个屏幕截图吗?出现波浪线?

最后我将尝试解释什么是地图:

map 只是一组键值对,也就是说,map 中的每个项目都有一些名称和一些值,类似于普通变量。地图的语法如下所示:

Map<TypeA, TypeB> myMap = {
  key1: value1,
  key2: value2,
  key3: value3,
  ...
  keyN: valueN,
};

其中typeA是key的类型,typeB是value的类型,例如:

Map<int, bool> myMap = {
  4: false,
  99: true,
  1927: false,
  777777: false,
  7: true,
};

如上,map 的键是 int 类型,map 的值是 bool 类型。

当然,您可以使用dynamic 来获得不同类型的密钥:

Map<String, dynamic> myMap = {
  'some string': 1,
  'some other string': true,
  'something else': ['aa','vv','gg',1],
};

上面的键的类型总是字符串,但是值的类型会改变,some string的类型是int,some other string的类型是bool,something else的类型是List , 列表有 3 个字符串和 1 个 int。

您的questions 变量实际上是一个地图列表:

var questions = [
      {
        'questiontext':'What\s your Age group?',
      'answers':['No','No','No','No'],
      },
      {
        'questiontext':'What\s your profession?',
      'answers':['student','teacher','government official','[private enterprise']
      },
      {
        'questiontext':'At what time do you get up?',
      'answers':['4am-6am','6am-7am','7am-8am','After 8am']}
      ];

这些是类型:

List<Map<String, dynamic>> questions = [
  {
    String: String,
    String: List<String>
  }
]

例如,var x = questions[0]['answers'],x 将是动态的,因为您的地图的值是动态的。

希望这个解释能让一切更清楚一点?

【讨论】:

  • 谢谢先生,代码现在可以工作了,至于']'错误,我不明白为什么会出现,现在它已经消失了。现在我也明白了地图的含义。再次感谢
猜你喜欢
  • 2021-11-25
  • 2018-10-27
  • 1970-01-01
  • 2019-11-29
  • 1970-01-01
  • 2022-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多