简体   繁体   English

Flutter/Dart:尽管设置了状态变量,但未设置

[英]Flutter/Dart: State variables not set despite being set

I simply cannot make heads or tails out of this.我根本无法从中做出正面或反面。 So, this is the main widget:所以,这是主要的小部件:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Anliegen Foo',
      home: Home(),
    );
  }
}

while the Home widget is supposed to be a stateful one and defined thus:而 Home 小部件应该是一个有状态的小部件并定义如下:

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  int _currentIndex = 42;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Foo - $_currentIndex"),
      ),
      body: Text('bar baz'),
    );
  }
}

Similarly to how the official docs recommend you do this.官方文档建议您这样做的方式类似。

You would expect the AppBar title to be "Foo - 42".您可能希望 AppBar 标题为“Foo - 42”。 But it is "Foo - 0", ie while the variable is found it is found to be null (and thus seemingly automatically interpreted as 0).但它是“Foo - 0”,即在找到变量时发现它为空(因此似乎自动解释为 0)。 The debugger says that the variable exists and is set to 42, both in the context of the class and the build function.调试器说该变量存在并且在类和构建函数的上下文中都设置为 42。 This also goes for anything else I try to declare - Lists, strings, whatever, all not initialized but at the same time initialized.这也适用于我尝试声明的任何其他内容 - 列表、字符串等等,都未初始化但同时已初始化。

But when I then do set the variable inside the build method like this:但是当我在 build 方法中设置变量时,如下所示:

@override
  Widget build(BuildContext context) {
    _currentIndex = 42;
[...]

now it begins to work.现在它开始工作了。

So, where am I going wrong here?那么,我哪里出错了?

Yes, thank you guys, a mere rebuild/hot restart was indeed the answer.是的,谢谢你们,仅仅重建/热重启确实是答案。 I was thrown by the fact that the debugger shows the variable just fine with the proper value while the Widget does rely on the old class definition from before the hot reload.我被调试器显示的变量以正确的值显示得很好,而小部件确实依赖于热重载之前的旧类定义这一事实让我感到震惊。

tl;dr: Restart or hot restart. tl;dr:重启或热重启。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM