flutter 错误缺少“StatefulWidget. createState”的具体实现,尝试实现缺少的方法,或者使类成为抽象类

vql8enpb  于 2023-05-19  发布在  Flutter
关注(0)|答案(1)|浏览(195)
import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget { 
   Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child:
            Container(
              height: 200,
              width: 100,
              color:  Colors.yellow,
        ),
      ),
    );
  }
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height,
            decoration: BoxDecoration(
                image: DecorationImage(
                    image: AssetImage("asset/image/Bestone.jpg")))));
  }
}

无论我使用什么,当我试图运行或编码时都会遇到问题。我得到这个错误。
缺少'StatefulWidget. createState'的具体实现。尝试实现缺少的方法,或者使类为MyApp()抽象

wvyml7n5

wvyml7n51#

StatefulWidget需要重写方法createState,因此必须重写该方法。删除构建方法并在MyApp中指定以下行

@override
_MyHomePageState createState() => _MyHomePageState();

完整的例子与适当的StateFulWidget

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String title;

  const MyHomePage({
    Key? key,
    required this.title,
  }) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

相关问题