initState() not called when building stateful widget - flutter

I am trying to build a widget and do something in the initState() function. I have done it before in other cases, but this time the initState() is just not called. I have put breakpoints, the application goes into the constructor (assert line) and the object in the assert is not null, so it should go on and initialize the state. But it doesn't, and I don't understand why.
Any help would be greatly appreciated. Thanks.
Here's the code:
class MyWidget extends StatefulWidget {
SomeOtherObject someOtherObject;
MyWidget({#required this.someOtherObject})
:
assert(someOtherObject != null)
;
#override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
#override
void initState() {
super.initState();
// widget.someOtherObject.addListener(update);
}
#override
Widget build(BuildContext context) {
// ...
}
}

I would redirect you to this answer: initState function is't be called in StatefulWidget by default
Your code works just fine in a DartPad, make sure you fully restart your app, not just hot reload. Often times for me, Flutter likes to use an old version of my app so I have to hot restart. Also, just so you know, any time you edit initState(), you MUST hot restart your app for the changes to take effect.

Related

What should I do when I have to use "void function() async" as a last resort in Flutter?

My function is as follows:
void function() async {
…
}
I used the above function in Widget build(BuildContext context).
Actually, I want it to be Future<void> function() async instead of void function() async.
However, I can't use await in Widget build(BuildContext context), so I can't use Future<void> function() async because Future requires await.
I shouldn't use FutureBuilder or then because I don't want to get the data in the function, I just want to run the function.
Appreciate if someone can advise. Thank you in advance!
You can define your function as future & call it in initState of StatefulWidget (without await)
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Future<void> myFutureFunction() async {
// some future work with
}
#override
void initState() {
super.initState();
// this will be called once, when this widget is apear to the screen
myFutureFunction();
}
#override
Widget build(BuildContext context) {
return SizedBox();
}
}
build method can run up to 60(maybe more with the newest phones)times per second, so it's not a good idea to run any heavy computation or API call in the build method. It's simply for building(widgets).
You may want to rethink your app architecture if you think you must.
Consider bloc pattern or just checkout other lifecycle methods for stateful widgets. This article has a list of them.
As for the question, async functions technically don't require you to await them. You can just call them without adding await in front of them.
If you have a warning, it might be coming from lint rules. Related rule.

How should I implement the init method? In a stateful or stateless widget?

What is the rule of thumb to use an initial method for a widget. Shall I use the:
A. classical stateful widget approach?
Or is it better to stick with the B. stateless widget approach?
Both seem to work from my testing. In terms of code reduction, it seems the B. approach is better, shorter, cleaner, and more readable. How about the performance aspect? Anything else that I could be missing?
Initializing a controller should be a one-time operation; if you do it on a StatelessWidget's build method, it will be triggered every time this widget is rebuilt. If you do it on a StatefulWidget's initState, it will only be called once, when this object is inserted into the tree when the State is initialized.
I was looking for initializing some values based on values passed in constructor in Stateless Widget.
Because we all know for StatefulWidget we have initState() overridden callback to initialize certain values etc. But for Stateless Widget no option is given by default. If we do in build method, it will be called every time as the view update. So I am doing the below code. It works. Hope it will help someone.
import 'package:flutter/material.dart';
class Sample extends StatelessWidget {
final int number1;
final int number2;
factory Sample(int passNumber1, int passNumber2, Key key) {
int changeNumber2 = passNumber2 *
2; //any modification you need can be done, or else pass it as it is.
return Sample._(passNumber1, changeNumber2, key);
}
const Sample._(this.number1, this.number2, Key key) : super(key: key);
#override
Widget build(BuildContext context) {
return Text((number1 + number2).toString());
}
}
Everything either a function or something else in widget build will run whenever you do a hot reload or a page refreshes but with initState it will run once on start of the app or when you restart the app in your IDE for example in StatefulWidget widget you can use:
void initState() {
super.initState();
WidgetsBinding.instance!
.addPostFrameCallback((_) => your_function(context));
}
To use stateful functionalities such as initState(), dispose() you can use following code which will give you that freedom :)
class StatefulWrapper extends StatefulWidget {
final Function onInit;
final Function onDespose;
final Widget child;
const StatefulWrapper(
{super.key,
required this.onInit,
required this.onDespose,
required this.child});
#override
State<StatefulWrapper> createState() => _StatefulWrapperState();
}
class _StatefulWrapperState extends State<StatefulWrapper> {
#override
void initState() {
// ignore: unnecessary_null_comparison
if (widget.onInit != null) {
widget.onInit();
}
super.initState();
}
#override
Widget build(BuildContext context) {
return widget.child;
}
#override
void dispose() {
if (widget.onDespose != null) {
widget.onDespose();
}
super.dispose();
}
}
Using above code you can make Stateful Wrapper which contains stateful widget's method.
To use Stateful Wrapper in our widget tree you can just wrap your widget with Stateful Wrapper and provide the methods or action you want to perform on init and on dispose.
Code available on Github
NOTE: You can always add or remove method from Stateful Wrapper Class according to your need!!
Happy Fluttering!!

Does StatefulWidget not rebuild State every time it has new data?

The widget TrainsPage is added to the build graph in main.dart, when the corresponding menu button is clicked. This is done twice: once when _routes is empty and a second time when _routes is filled.
Widget pageSelector() {
if (_selectedIndex == 2) {
return new TrainsPage(routes: _routes);
} else
return Text("");
}
In TrainsPage.dart, I have the code for the stateful widget TrainsPage.
class TrainsPage extends StatefulWidget {
const TrainsPage({Key? key, required this.routes}) : super(key: key);
final List<RSRoute> routes;
#override
_TrainsPageState createState() => _TrainsPageState();
}
class _TrainsPageState extends State<TrainsPage> {
List<RSRoute> _routes = List.empty();
#override
void initState() {
super.initState();
this._routes = new List<RSRoute>.from(widget.routes);
Now, the second time, TrainsPage gets called in main.dart (now with routes filled), initState() of _TrainsPageState is not called, which is responsible to read the data in routes. And because routes was empty the first time, there is nothing in display on the trains page.
Why does TrainsPage not rebuild _TrainsPageState, when it clearly got new data in the constructor?
This is exactly why the State exists : to keep the state of the current context alive even when the widget is rebuild.
If it was recreated each time the statefull widget is rebuild it could not keep the state of its own variables.
class MyWidget extends StatelessWidget {
var _someStateVariable = 0;
#override
void build(BuildContext context){
// here an action that increment _someStateVariable
}
}
Here _someStateVariable would be reset to 0 at each rebuild. Or if we wanted a StateFullWidget in the first place it's because we'll update this variable later and want to keep its updated value through the multiple widget rebuilds.
If you don't have such state variable to maintain maybe you don't need a StateFullWidget here.
Now to the solution to your problem : you can override didUpdateWidget instead of initstate since it will be called at each widget rebuild :
#override
void didUpdateWidget() {
didUpdateWidget();
_routes = new List<RSRoute>.from(widget.routes);
}

Flutter & Dart : What is mounted for?

I am seeing this mounted syntax. What is it for? Could you give me sample?
TL;DR: A widget is mounted if it has state. If the widget is no longer mounted, i.e it has been closed or disposed, its state can no longer be updated. Therefore, we check if a widget is mounted to determine its state can still be updated.
Mounting is the process of creating the state of a StatefulWidget and attaching it to a BuildContext.
Take the following example:
class Example extends StatefulWidget {
#override
_ExampleState createState() => _ExampleState();
}
class _ExampleState extends State<Example> {
#override
Widget build(BuildContext context) {
return Container(
);
}
}
The widget is assigned its state (_ExampleState) when the createState() method is called.
As soon as it is assigned its state, the widget becomes mounted.
Why is that important?
When a widget is unmounted in the dispose method of a StatefulWidget, it loses its state. This happens when it is no longer in the tree. I.e, it is has been closed, or no longer exists.
#override
void unmount() {
super.unmount();
state.dispose();
assert(() {
if (state._debugLifecycleState == _StateLifecycle.defunct)
return true;
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('${state.runtimeType}.dispose failed to call super.dispose.'),
ErrorDescription(
'dispose() implementations must always call their superclass dispose() method, to ensure '
'that all the resources used by the widget are fully released.'
),
]);
}());
// This is the key
state._element = null;
}
This basically means the state can't be updated and setState can no longer be called. So when you check if a widget is mounted, you're checking if its state can still be updated.
Use case:
Going back to our example Stateful Widget example, let's say we had a number that we wanted to update 30 seconds after the Widget is created.
class Example extends StatefulWidget {
#override
_ExampleState createState() => _ExampleState();
}
class _ExampleState extends State<Example> {
int count = 0;
#override
void initState() {
Future.delayed(const Duration(seconds: 30), () {
setState(() => count = 5);
});
super.initState();
}
#override
void dispose() {
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text('count $count'),
));
}
}
Our code will work fine, as long as the widget is disposed of or closed. If it is disposed of, we will get the famous error:
setState() called after dispose()
To prevent this, all we have to do is check if our widget still has state before updating it.
#override
void initState() {
Future.delayed(const Duration(seconds: 30), () {
if (mounted) setState(() => count = 5);
});
super.initState();
}
It represents whether a state is currently in the widget tree.
https://api.flutter.dev/flutter/widgets/State/mounted.html
You shouldn't call setState() on a state that is not currently in the tree.
Edit: The other answer provides a simple example. I should also mention that the described behavior is evident from the StatefulWidget lifecycle: https://flutterbyexample.com/lesson/stateful-widget-lifecycle
It's opinionated, but as far as I can see, it's a rare ocasion when you have to check for mounted, because you unsubscribe from outside events in dispose(). Even the Future from the example could be wrapped in CancelableOperation to cancel it in dispose(), which is before mounted == false

why do we need the didUpdateWidget and build method in a statefull widget?

why do we need the didUpdateWidget method in a state?
Build is called anyway, cant we add the logic there too?
The only difference is, that we dont have a reference to the old widget as paramter or do i miss something?
Yes, you can implement logic in the build method when something is reloaded on your screen.
didUpdateWidget is called every time when the corresponding widget is recreated
But, the difference is that, when we can compare some values and based on those values we can take decisions on the app.
Example:
class MyApp extends StatefulWidget {
int getInitialValue() {
return 1;
}
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
int _currentValue = 10;
#override
void didUpdateWidget(MyApp oldWidget) {
if(oldWidget.getInitialValue() != _currentValue) {
// Perform animation
// Fetch data from server
}
}
}
Above is just an example of how we can use didUpdateWidget(), we can do similar stuff for many other scenarios