0

I have a page in my flutter app that is only built to display my app's logo and then go to another page. For some reason I can not figure out it runs the build method multiple times even though it is called once.

Here is the code:

class LoadingPage extends StatelessWidget {
  int i = 0;
  @override
  Widget build(BuildContext context) {
    i++;
    print(i);
    test(context);
    test2();
    return Scaffold(
      backgroundColor: Colors.lightBlue,
      body: SafeArea(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Image.asset("assets/images/logo.png"),
            SizedBox(
              height: Responsive.deviceHeight(context) * 0.05,
            ),
            LoadingRotating.square(
              backgroundColor: Colors.lightBlue,
              borderColor: Colors.white,
              borderSize: 5.0,
            ),
          ],
        ),
      ),
    );
  }

  void test(BuildContext context) {
    Future.delayed(const Duration(seconds: 5), () {
      print("H");
      Navigator.of(context).pushAndRemoveUntil(
        MaterialPageRoute(builder: (context) => ProductListPage()),
        (Route<dynamic> route) => false,
      );
    });
  }

  void test2(){
    print("H2");
  }
}

I have expected to print the following:

1
H2
H

But the result is:

I/flutter (20904): 1
I/flutter (20904): H2
I/flutter (20904): 1
I/flutter (20904): H2
I/flutter (20904): H
I/flutter (20904): H

Can someone explain this behavior?

Thank you

1 Answers1

2

You should treat the build method as if it will be called multiple times. There is no guarantee that it will only be called once. Check this answer for more detailed information: How to deal with unwanted widget build?

puelo
  • 5,464
  • 2
  • 34
  • 62