Created
June 11, 2018 17:53
-
-
Save cfkloss/e7d58eb8f3b11e4b96d2d023bd7a1f85 to your computer and use it in GitHub Desktop.
StatefulWidget rebuilding unnecessarily after Navigator.push()/pop()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
home: Page1(), | |
); | |
} | |
} | |
class Page1 extends StatefulWidget { | |
@override | |
Page1State createState() { | |
return new Page1State(); | |
} | |
} | |
class Page1State extends State<Page1> { | |
var i = 0; | |
@override | |
Widget build(BuildContext context) { | |
i++; | |
print("rebuild $i"); | |
return Scaffold(appBar: AppBar(title: Text('Page1')), | |
body: Center( | |
child: Column(mainAxisAlignment: MainAxisAlignment.spaceAround, | |
children: <Widget>[ | |
Text('Page1 build counter: $i'), | |
RaisedButton( | |
child: Text('Navigate to page 2'), | |
onPressed: () { | |
Navigator.push(context, | |
MaterialPageRoute(builder: (_) { | |
print('inside MaterialPageRoute builder'); | |
return Scaffold( | |
appBar: AppBar(title: Text('Page2')), | |
body: Center(child: Text('$i'))); | |
}) | |
); | |
}, | |
) | |
]) | |
)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment