本文介绍了默认情况下,不会在StatefulWidget中调用initState函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢您的关注.我是扑扑的初学者.我不知道为什么默认情况下不调用initState函数.由于未运行print(list [0])语句.

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,
      ),
    );
  }
}

推荐答案

我尝试了您的代码,但仍正常打印.请确保您重新运行代码,请勿执行热重装,因为initState()仅被调用一次.该文件说:

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:

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

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

这意味着您必须将所有代码放在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"
}

这篇关于默认情况下,不会在StatefulWidget中调用initState函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-13 00:56