简体   繁体   中英

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:

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". But it is "Foo - 0", ie while the variable is found it is found to be null (and thus seemingly automatically interpreted as 0). The debugger says that the variable exists and is set to 42, both in the context of the class and the build function. 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:

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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