title: Preserve widget state when temporarily removed from tree in Flutter
body: <p>I'm trying to preserve the state of a widget, so that if I temporarily remove the stateful widget from the widget tree, and then re-add it later on, the widget will have the same state as it did before I removed it. Here's a simplified example I have:</p>
  <pre><code>import 'package:flutter/material.dart';
  
  void main() =&gt; runApp(MyApp());
  
  class MyApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: MyHomePage(title: 'Flutter Demo Home Page'),
      );
    }
  }
  
  class MyHomePage extends StatefulWidget {
    MyHomePage({Key key, this.title}) : super(key: key);
  
    final String title;
  
    @override
    _MyHomePageState createState() =&gt; _MyHomePageState();
  }
  
  class _MyHomePageState extends State&lt;MyHomePage&gt; {
    bool showCounterWidget = true;
    @override
    Widget build(BuildContext context) {
  
      return Material(
        child: Center(
          // Center is a layout widget. It takes a single child and positions it
          // in the middle of the parent.
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: &lt;Widget&gt;[
              showCounterWidget ? CounterButton(): Text(&quot;Other widget&quot;),
              SizedBox(height: 16,),
              FlatButton(
                child: Text(&quot;Toggle Widget&quot;),
                onPressed: (){
                  setState(() {
                  showCounterWidget = !showCounterWidget;
                });
                  },
              )
            ],
          ),
        ),
      );
    }
  }
  
  class CounterButton extends StatefulWidget {
    @override
    _CounterButtonState createState() =&gt; _CounterButtonState();
  }
  
  class _CounterButtonState extends State&lt;CounterButton&gt; {
    int counter = 0;
  
    @override
    Widget build(BuildContext context) {
      return MaterialButton(
        color: Colors.orangeAccent,
        child: Text(counter.toString()),
        onPressed: () {
          setState(() {
            counter++;
          });
        },
      );
    }
  }
  </code></pre>
  <img src="https://i.stack.imgur.com/pQfNM.gif" width="280" >
  <p>Ideally, I would not want the state to reset, therefor the counter would not reset to 0, how would I preserve the state of my counter widget?</p>