Another exception was thrown: type 'MyApp' is not a subtype of type 'StatelessWidget'

你说的曾经没有我的故事 提交于 2019-11-30 16:23:23

问题


I have just started using Flutter and i'm having this problem while running my code "Another exception was thrown: type 'MyApp' is not a subtype of type 'StatelessWidget'". And the interesting part is that i dont even have this 'StatelessWidget' in my code.

   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(),
              )
            ],
          )),
    );
  }
}

I am really lost and would aprecciate some help!

Thanks,


回答1:


As Jonah Williams said,

If you changed MyApp from a StatelessWidget to a StatefulWidget you need to hot restart, since it is invoked in main

This has been explained multiple times in live coding sessions, that when you make changes in functions like initState(), you have to restart the app. A similar case applies for you, when you changed state related properties of the MyApp widget you need to restart your app for those changes to take effect.

Basically, when you hot reload the app, it calls the build() function, initState() is called only when you restart the app, so that the app reinitiates everything including the widget whose initState() function you changed.



来源:https://stackoverflow.com/questions/51334839/another-exception-was-thrown-type-myapp-is-not-a-subtype-of-type-statelesswi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!