无法使用 Flutter Stateful 小部件

Unable to work with Flutter Stateful widget

我是拉维。我对 Flutter 很陌生,但对编程并不陌生。我一直在使用 Flutter 的有状态小部件。因为我是这个 SDK 的新手,所以我无法弄清楚为什么我的状态没有得到更新。我所做的只是编写了一些代码,每当单击按钮时就会增加一个数字,而且我知道我们必须使用有状态的小部件才能实时更新任何数据。但我的代码无法正常工作。谁能帮我解决这个问题。

import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
int level = 0;
return MaterialApp(
  home: Scaffold(
      appBar: AppBar(
        title: Text('Stateful Widget'),
      ),
      body: Center(
        child: Column(
          children: [
            Text('$level'),
            RaisedButton(
              child: Text('Increment'),
              onPressed: () {
                setState(() {
                  level = level + 1;
                  print(level);
                });
              },
            ),
          ],
        ),
      )),
);
}
}

Console: 
Performing hot reload...
Syncing files to device sdk gphone x86 arm...
Reloaded 1 of 513 libraries in 1,722ms.
I/flutter ( 8886): 1

问题在于您的 level 变量的范围。它不应该在您的 build 方法中,而应该在您的 class

class _MyAppState extends State<MyApp> {
//Moved level here.
  int level = 0;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Stateful Widget'),
        ),
        body: Center(
          child: Column(
            children: [
              Text('$level'),
              RaisedButton(
                child: Text('Increment'),
                onPressed: () {
                  setState(() {
                    level = level + 1;
                    print(level);
                  });
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}