【发布时间】:2019-01-15 02:47:23
【问题描述】:
感谢您的关注。我是颤振的初学者。我不知道为什么默认不调用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,
),
);
}
}
【问题讨论】:
-
什么是 MainPage()?你怎么知道 initState() 没有被调用?
-
MainPage()是一个小部件。因为print(list[0])语句没有被调用。 -
我试过你的代码,打印正常
-
我所有的控制台显示如下。
Performing hot reload... Syncing files to device iPhone XR... Reloaded 0 of 420 libraries in 822ms. -
能不能重新运行试试,不能热加载。因为 initSate 只被调用一次。另外,请尝试下面的答案。
标签: flutter