我正在学习Flutter,在构建一个简单的应用程序时遇到了这种奇怪的行为。我已经创建了一个自定义的有状态小部件,而我根本无法在另一个有状态小部件中使用它。这是预期的行为还是我在这里丢失了一些东西?
错误是:
和
编码:
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Stateful Widget 02',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Testing nested Stateful Widgets'),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
new TextCard(),
new TextCard()
],
),
),
);
}
}
class TextCard extends StatefulWidget {
@override
State<StatefulWidget> createState() {
_TextCardState createState() => new _TextCardState();
}
}
class _TextCardState extends State<TextCard> {
@override
Widget build(BuildContext context) {
return new Card(
child: new Text('12312')
);
}
}
最佳答案
您以错误的方式覆盖了createState()
中的TextCard
。
替换:
createState() {
_TextCardState createState() => new _TextCardState();
}
使用:
@override
_TextCardState createState(){
return new _TextCardState();
}