我刚开始使用 Flutter,在运行我的代码时遇到了这个问题 “引发了另一个异常:'MyApp' 类型不是'StatelessWidget' 类型的子类型”。 有趣的是,我的代码中什至没有这个“StatelessWidget”。
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
// TODO: implement createState
return _MyAppState();
}
}
class _MyAppState extends State<MyApp> {
List<String> _bars = ['Olivio bar'];
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Drinkzz'),
),
body: Column(
children: [
Container(
margin: EdgeInsets.all(10.0),
child: RaisedButton(
onPressed: () {
_bars.add('Riviera Bar');
},
child: Text('Add new Bar!'),
),
),
Column(
children: _bars
.map((element) => Card(
child: Column(
children: <Widget>[
Image.asset('assets/olivio.jpg'),
Text(element)
],
),
))
.toList(),
)
],
)),
);
}
}
我真的迷路了,希望能得到一些帮助!
谢谢,
最佳答案
作为 Jonah Williams said ,
If you changed
MyApp
from aStatelessWidget
to aStatefulWidget
you need to hot restart, since it is invoked in main
这在实时编码 session 中已多次解释,当您对 initState()
等函数进行更改时,您必须重新启动应用程序。类似的情况也适用于您,当您更改 MyApp 小部件的状态相关属性时,您需要重新启动应用程序才能使这些更改生效。
基本上,当你热重载应用时,它会调用build()
函数,initState()
只有在你重启时才会被调用应用程序,以便应用程序重新启动所有内容,包括您更改了 initState()
函数的小部件。
关于flutter - 另一个异常被抛出 : type 'MyApp' is not a subtype of type 'StatelessWidget' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51334839/