2

I am trying to understand why the Flutter / Dart HotReload does not work if I reference the appBar: widget as opposed to defining the code inline. Why?

Here is the sample code:

class AppBarWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold( 
      appBar: appBar, 
    );
  }
}

AppBar appBar = AppBar(
  title: new Text("App Title"),
);

Notice appBar: appBar is a reference to the AppBar(...) widget definition. In this case, if I change the title: property text, it will not hot reload even though both IDE (VSCode or AStudio) says it reloads. I need to rebuild to make it work.

But if I move the AppBar(...) widget definition into appBar: AppBar(...) and change the title, it Hot Reloads.

1
  • Ok, I thought to copy the AppBar appBar=AppBar(...) as a method inside the class. Hot reload works. So I will assume functions outside a class do not hot reload? Commented Mar 24, 2019 at 0:08

1 Answer 1

2

This happens because Flutter's hot-reload is "stateful". It preserves the state of all variables – including the variable you defined.

As such, while you can change the sources of a variable, it will keep its previous state.

In any cases, you shouldn't extract widgets as global variables – but instead, extract them as StatelessWidget and use const constructor.

This has the same performances benefits while being compatible with hot-reload.

class MyAppBar extends StatelessWidget implements PreferredSizeWidget {
  const MyAppBar({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return AppBar(
      title: const Text('App title'),
    );
  }

  @override
  Size get preferredSize => const Size.fromHeight(kToolbarHeight);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.