Home > database >  Flutter: The element type 'String' can't be assigned to the list type 'Widget�
Flutter: The element type 'String' can't be assigned to the list type 'Widget�

Time:12-17

First off, I am really really new

I do not understand why these two errors are appearing : 1.The element type 'String' can't be assigned to the list type 'Widget'. 2.Expected to find ']'.

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),
        ),
      ),
    );
  }
}

Also i did not exactly understand what maps in dart was, would be really halpful if someone gave a breif overview

If you have read till here THANK YOU

CodePudding user response:

...(questions[_questionindex]['answers']) as List<String>.map((answer){
              Answer(_answerQuestion,answer);
            }).toList()

there are 2 reasons why the above code is causing you problems.

  1. List<String>.map(... is confusing dart, because it thinks you are calling some method on List<String>, to fix this, surround it with another pair of parenthesis
...((questions[_questionindex]['answers']) as List<String>).map((answer){
              Answer(_answerQuestion,answer);
            }).toList()
  1. the map method doesn't return anything, you most likely forgot to add a return statement, to fix this just add the return statement:
...((questions[_questionindex]['answers']) as List<String>).map((answer){
              return Answer(_answerQuestion,answer);
            }).toList()

Regarding Expected to find ']'. Sorry, but after copying and pasting your code in my editor, I did not get this error... Would you mind showing a screenshot of exactly where the squiggly line appears?

Finally I will attempt to explain what a map is:

a map is just a set of key-value pairs, that is to say, every item in a map has some name and some value, similar to a normal variable. A map's syntax looks like this:

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

Where typeA is the type of the key and typeB is the type of the value, so for example:

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

above, the map's keys have an int type and the map's values have a bool type.

Of course, you can use dynamic in order to have different types of keys:

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

above the type of the keys is always string, but the values type changes, for some string, the type is int, for some other string the type is bool, and for something else, the type is List, the list there has 3 strings and one int.

your questions variable is actually a list of maps:

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']}
      ];

these are the types:

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

so for example, var x = questions[0]['answers'], x will be dynamic, because the values of your map are dynamic.

Hopefully this explanation makes everything a bit clearer?

  • Related