You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter代码运行报错:未实现StatefulWidget.createState方法

问题解决:StatefulWidget.createState未实现错误

错误根源是方法名拼写错误:你在MyApp类里写的creteState少了一个字母a,正确的方法名应该是createState。Dart无法识别这个错误的方法名,因此判定你没有实现StatefulWidget要求的createState抽象方法。

修正后的完整代码:

import "package:flutter/material.dart";

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

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() { // 修正拼写错误
    return MyAppState();
  }
}

class MyAppState extends State<MyApp> {
  var questionIndex = 0;

  void AnswerQuestion() {
    setState(() {
      questionIndex = questionIndex + 1;
    });
    print(questionIndex);
  }

  @override
  Widget build(BuildContext context) {
    var questions = [
      "whats your favorite color",
      "whats your favorite animal",
    ];
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('my first app'),
        ),
        body: Column(children: [
          Text(questions[questionIndex]),
          ElevatedButton(child: Text('answer1'), onPressed: AnswerQuestion),
          ElevatedButton(
              child: Text('answer2'),
              onPressed: () => print("answer 2 choosen")),
          ElevatedButton(child: Text('answer3'), onPressed: AnswerQuestion),
        ]),
      ),
    );
  }
}

额外建议:

  • Dart命名规范中,方法名应使用小驼峰(answerQuestion而非AnswerQuestion),遵循规范可提升代码可读性。
  • 当questionIndex超过数组长度时会触发报错,可在AnswerQuestion中添加判断逻辑,比如questionIndex = (questionIndex + 1) % questions.length;,实现问题循环切换。

内容的提问来源于stack exchange,提问作者ramanujans alkhazarim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 06:57:10