2

我是拉维。我对 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

Flutter Stateful 小部件演示

4

1 回答 1

3

问题在于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);
                  });
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}
于 2020-09-01T13:55:25.867 回答