gpt4 book ai didi

flutter - 无法使用Flutter Stateful小部件

转载 作者:行者123 更新时间:2023-12-03 02:52:07 25 4
gpt4 key购买 nike

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

最佳答案

问题出在您的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);
});
},
),
],
),
),
),
);
}
}

关于flutter - 无法使用Flutter Stateful小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63689086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com