引发了另一个异常:类型'String'不是'score'类型'int'的子类型

时间:2020-09-02 17:21:07

标签: flutter dart

使用以下代码,出现错误:

import 'package:flutter/material.dart';
import './quiz.dart';
import './result.dart';

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

class _MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState

    return _MyAppState();
  }
}

class _MyAppState extends State<_MyApp> {
  final _questions = const [
    {
      'questionText': 'What\'s your favourite color ?',
      'answers': [
        {'text': 'Black', 'score': '1'},
        {'text': 'Red', 'score': '2'},
        {'text': 'Green', 'score': '3'},
        {'text': 'Yellow', 'score': '0'},
      ],
    },
    {
      'questionText': 'what\'s your favourite animal ?',
      'answers': [
        {'text': 'pig', 'score': '0'},
        {'text': 'camel', 'score': '2'},
        {'text': 'snake', 'score': '3'},
        {'text': 'lion', 'score': '1'},
      ],
    },
    {
      'questionText': 'What\'s your favourite instructor ?',
      'answers': [
        {'text': 'Niraj', 'score': '1'},
        {'text': 'Torpea', 'score': '0'},
        {'text': 'Nippo', 'score': '1'},
        {'text': 'senihang', 'score': '3'},
      ],
    },
  ];
  var _questionIndex = 0;
  var _totalScore = 0;

  void _answerQuestion(int score ) {
    _totalScore = score + _totalScore;
    setState(() {
      _questionIndex = _questionIndex + 1;
    });
    print(_questionIndex);
    if (_questionIndex < _questions.length) {
      print('We have more questions !');
    } else {
      print('No more questions ! ');
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("My First App"),
        ),
        body: _questionIndex < _questions.length
            ? Quiz(
                answerQuestion: _answerQuestion,
                questionIndex: _questionIndex,
                questions: _questions,
              )
            : Result(_totalScore),
      ),
    );
  }
}



import 'package:flutter/material.dart';
import './answer.dart';
import './question.dart';

class Quiz extends StatelessWidget {
  final List<Map<String, Object>> questions;
  final int questionIndex;
  final Function answerQuestion;
  Quiz({
    @required this.questions,
    @required this.answerQuestion,
    @required this.questionIndex,
  });
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Question(
          questions[questionIndex]['questionText'],
        ),
        ...(questions[questionIndex]['answers'] as List<Map<String, Object>>)
            .map((answer) {
          return Answer(() => answerQuestion(answer['score']), answer['text']);
        }).toList()
      ],
    );
  }
}


import 'package:flutter/material.dart';

class Result extends StatelessWidget {
  final int resultScore;
  Result(this.resultScore);

  String get resultPhrase {
    String resultText;
    if (resultScore <= 3) {
      resultText = ' You are awesome and innocent! ';
    } else if (resultScore <= 4) {
      resultText = ' Pretty Likeable! ';
    } else if (resultScore <= 5) {
      resultText = ' You are ... Strange ? !';
    } else {
      resultText = ' you are so bad ! ..';
    }
    return resultText;
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text(
        resultPhrase,
        style: TextStyle(fontSize: 36, fontWeight: FontWeight.bold),
        textAlign: TextAlign.center,
      ),
    );
  }
}


import 'package:flutter/material.dart';

class Question extends StatelessWidget {
  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,
      ),
    );
  }
}

import 'package:flutter/material.dart';

class Answer extends StatelessWidget {
  final Function selectHandler;
  final String answerText;
  Answer(this.selectHandler, this.answerText);
  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      child: RaisedButton(
        color: Colors.blue,
        textColor: Colors.white,
        child: Text(answerText),
        onPressed: selectHandler,
      ),
    );
  }
}


i am getting error when i am running my app. 

An Observatory debugger and profiler on A1601 is available at: http://127.0.0.1:57877/pv6MXqvHOCg=/
I/flutter ( 7861): ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
I/flutter ( 7861): The following _TypeError was thrown while handling a gesture:
I/flutter ( 7861): type 'String' is not a subtype of type 'int' of 'score'
I/flutter ( 7861): When the exception was thrown, this was the stack:
I/flutter ( 7861): #0      Quiz.build.<anonymous closure>.<anonymous closure> (package:youtube_course_01/quiz.dart:23:45)
I/flutter ( 7861): #1      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:992:19)
I/flutter ( 7861): #2      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:1098:38)
I/flutter ( 7861): #3      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:184:24)
I/flutter ( 7861): #4      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:524:11)
I/flutter ( 7861): #5      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:284:5)
I/flutter ( 7861): #6      BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:219:7)
I/flutter ( 7861): #7      PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:477:9)
I/flutter ( 7861): #8      PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:78:12)
I/flutter ( 7861): #9      PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:124:9)
I/flutter ( 7861): #10     _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:377:8)
I/flutter ( 7861): #11     PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:122:18)
I/flutter ( 7861): #12     PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:108:7)
I/flutter ( 7861): #13     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:220:19)
I/flutter ( 7861): #14     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:200:22)
I/flutter ( 7861): #15     GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:158:7)
I/flutter ( 7861): #16     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:104:7)
I/flutter ( 7861): #17     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:88:7)
I/flutter ( 7861): #21     _invoke1 (dart:ui/hooks.dart:267:10)
I/flutter ( 7861): #22     _dispatchPointerDataPacket (dart:ui/hooks.dart:176:5)
I/flutter ( 7861): (elided 3 frames from dart:async)
I/flutter ( 7861): Handler: "onTap"
I/flutter ( 7861): Recognizer:
I/flutter ( 7861):   TapGestureRecognizer#b5bcf
I/flutter ( 7861): ════════════════════════════════════════════════════════════════════════════════════════════════════
I/flutter ( 7861): Another exception was thrown: type 'String' is not a subtype of type 'int' of 'score'

1 个答案:

答案 0 :(得分:1)

这里的问题是您正在发送一个等待int的字符串。 如果我没记错的话,错误就在这行:return Answer(() => answerQuestion(answer['score']) 我相信您应该这样做return Answer(() => answerQuestion(int.parse(answer['score']))