默认情况下,StatefulWidget 中不调用 initState 函数

xso*_*ong 3 flutter

感谢您的关注。我是颤振的初学者。我不知道为什么initState默认情况下不调用该函数。因为没有运行 print(list[0]) 语句。

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,
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

Phu*_*ran 6

我试过你的代码,它仍然正常打印。请确保您重新运行代码,不要进行热重载,因为 initState() 仅被调用一次。该文件说:

框架将为其创建的每个 [State] 对象只调用一次此方法。

我从 initState() 的文档中选择了你应该遵循的一件事:

如果您覆盖它,请确保您的方法以调用 super.initState() 开始。

这意味着您必须将所有代码放在 super.initState() 下,如下所示:

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

    list.add(MainPage());
    print('initState() ---> ${list[0]}'); // This will print "initState() ---> MainPage"
}
Run Code Online (Sandbox Code Playgroud)