Flutter创建Stateful Widget时抛出UnimplementedError问题求助
解决Flutter Stateful Widget的UnimplementedError问题
嘿,作为Flutter新手遇到这个问题太正常啦,我一眼就瞅出问题在哪了!
你定义的MyApp是一个StatefulWidget,这类组件必须通过createState()方法返回对应的State子类实例,但你现在的代码里只是保留了IDE自动生成的throw UnimplementedError();——这就是程序抛出错误的核心原因:你根本没正确实现这个必填方法,反而让它直接抛出了「未实现」的错误。
核心修正点
把createState()方法改成返回你已经写好的MyAppState实例就行,不需要返回null(StatefulWidget的createState要求必须返回非null的State对象)。
修正后的MyApp类代码可以写成这样:
class MyApp extends StatefulWidget { @override State<MyApp> createState() { return MyAppState(); // 嫌麻烦的话,还可以用更简洁的箭头函数写法: // return MyAppState(); } }
完整修正后的代码
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatefulWidget { @override State<MyApp> 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 = [ "What's your favourite color?", "What's your favourite animal?", ]; return MaterialApp( home: Scaffold( appBar: AppBar( title: Text( "My First App", ), ), body: Column( children: [ Text( questions[questionIndex], ), RaisedButton( child: Text("Answer 1"), onPressed: answerQuestion, ), RaisedButton( child: Text("Answer 2"), onPressed: answerQuestion, ), RaisedButton( child: Text("Answer 3"), onPressed: answerQuestion, ) ], ), ), ); } }
最后提个小技巧:以后写StatefulWidget时,可以直接用Flutter的代码模板快速生成,这样就不会漏掉createState的正确实现啦~
内容的提问来源于stack exchange,提问作者Soun
相关产品推荐
相关产品推荐

