gpt4 book ai didi

flutter - StatefulWidget 默认不调用 initState 函数

转载 作者:IT王子 更新时间:2023-10-29 06:58:55 24 4
gpt4 key购买 nike

感谢您的关注。我是 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,
),
);
}
}

最佳答案

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

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

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

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

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

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

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

关于flutter - StatefulWidget 默认不调用 initState 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54192066/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com