Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initState function is't be called in StatefulWidget by default

Tags:

flutter

Thanks for your attention. I'm a beginner of flutter. I don't know why the initState function isn't called by default. Because of the print(list[0]) statement is not be run.

import 'package:flutter/material.dart';
import 'main_page/main_page.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _MyHomePage();
}

class _MyHomePage extends State<MyHomePage> {
  int _currentIndex = 0;
  List<Widget> list = List();

  @override
  void initState() {
    list.add(MainPage());
    print(list[0]);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: MainPage(),
      bottomNavigationBar: BottomNavigationBar(
        items: [
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            title: Text('Home')
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.person),
            title: Text('Me')
          ),
        ],
        currentIndex: _currentIndex,
        onTap: (int index) {
          setState(() {
            _currentIndex = index;
          });
        },
        type: BottomNavigationBarType.fixed,
      ),
    );
  }
}
like image 723
xsong Avatar asked Aug 01 '26 12:08

xsong


1 Answers

I tried your code and it still printed as normal. Please make sure you RE-RUN the code, don't do hot reloading since initState() is called only once. The document says:

The framework will call this method exactly once for each [State] object it creates.

One thing I pick from the documentation of initState() that you should follow:

If you override this, make sure your method starts with a call to super.initState().

That means you have to put all code under super.initState(), like below:

@override
void initState() {
    super.initState();

    list.add(MainPage());
    print('initState() ---> ${list[0]}'); // This will print "initState() ---> MainPage"
}
like image 75
Phuc Tran Avatar answered Aug 03 '26 13:08

Phuc Tran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!