3

I have a simple app, it has named route in an appbar to a stateful widget. Currently, whenever I navigate away from the stateful widget and back again, the stateful widget loses its state (in this case my counter goes back to 0). I'd like the stateful widget to keep its state, but I'm not sure what I'm doing wrong. Do I need to explicitly keep state around? How? Should I be using didUpdateWidget to transfer state? Or something else?

This is my main.dart:

import 'dart:async';

import 'package:flutter/material.dart';
import './pages/home_page.dart';
import './pages/counter_page.dart';


void main()
{
  CounterPage counterPage = new CounterPage();
  return runApp(new MaterialApp(
    home: new HomePage(),
    theme: new ThemeData.dark(),
    routes: <String, WidgetBuilder> {
      "main": (BuildContext context) => new HomePage(),
      'counter_page': (BuildContext context) {
          return counterPage;
        }
    },
  ));
}

This is the counter_page.dart

import 'dart:async';

import 'package:flutter/material.dart';

class CounterPage extends StatefulWidget {
  static String route = "counter_page";

  CounterPage();
  @override
  _CounterPageState createState() => _CounterPageState();
}

class _CounterPageState extends State<CounterPage> {
  int _counter;

  @override
    void initState() {
      super.initState();
      _counter = 0;
    }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Count"),
      ),
      body: new Text("$_counter"),
      floatingActionButton: new FloatingActionButton(
        onPressed: () => setState(() {_counter += 1;}),
        tooltip: 'Count',
        child: new Icon(Icons.refresh),
      ),
    );
  }
}
Jordan
  • 476
  • 7
  • 16
  • 1
    Ideally you'd keep the state outside of widgets entirely like using Redux. See also https://youtu.be/RS36gBEp8OI – Günter Zöchbauer Jul 11 '18 at 08:09
  • manage state with redux or BLoC. see this BLoC example https://www.youtube.com/watch?v=ALcbTxz3bUw – nonybrighto Jul 11 '18 at 09:12
  • 1
    These are not acceptable answers. Many flutter widgets maintain their own state, which you can not extract, like TexrField. Would love to know if this is possible somehow. – shawnblais Mar 19 '20 at 02:21
  • 1
    @shawnblais did you manage to solve this? I'm in exactly this predicament at the moment. – rufw91 Jul 07 '20 at 06:45
  • Not using Navigator, but you can get a this behavior using IndexedStack, AnimatedSwitcher, or your own simple Stack setup and assigning GlobalKey() for each "page" widget – shawnblais Jul 19 '20 at 05:50

1 Answers1

0

There are multiple ways to handle state management in Flutter, but one way of doing this is by using the provider package. With this, even if the Screen gets rebuilt multiple times, state management won't be affected.

Omatt
  • 8,564
  • 2
  • 42
  • 144