October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

How to Manage Game State and Undo Moves in Flutter

Keep game rules in a model or controller, publish each legal move as one state transition, and choose snapshot or command history to support undo and redo.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Keep the authoritative game state in a model or controller above the widgets that display it. Treat each legal move as one transition from the current state to a new state, then rebuild the board and related controls from that state. For undo and redo, use immutable snapshots for compact games or reversible move records when snapshots would be costly; Flutter’s UndoHistory<T> can handle keyboard undo for a ValueNotifier, but it does not implement game rules or move controls for you.

Where should game state live?

Put state shared by the board, score, turn indicator, and move controls in a model or controller above those widgets. Widgets should describe the current view, not serve as the authoritative record of the game. When the model changes, Flutter rebuilds the parts of the tree that depend on it. This follows Flutter’s declarative approach to UI and the distinction between application logic and widget construction in its simple app state management guide.

As an Amazon Associate I earn from qualifying purchases.

For a small, self-contained screen, local widget state may be sufficient. Once multiple widgets need the same game state—or game logic needs to be testable independently of the UI—move that state into a model or controller. Flutter does not prescribe one state-management package for every game. The choice should fit the app’s structure rather than determine where game rules belong.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How should a move update the board?

Make a move a single explicit state transition. A controller method should check legality against the current state, compute the next state, and publish the change once. An illegal move that changes nothing should not notify listeners unless the app separately changes something visible, such as an error message.

  1. Validate: Check whether the proposed move is legal for the current game state.
  2. Compute: Produce the next state from the current state and move.
  3. Publish: Replace the current state and notify the UI once.

With Flutter’s ChangeNotifier pattern, the model calls notifyListeners() after a meaningful mutation. If using Provider, place listening Consumer widgets deep in the tree so a game-state change rebuilds only the UI that needs it, rather than a larger screen than necessary. Flutter’s guide describes ChangeNotifier, ChangeNotifierProvider, and Consumer as one approach, not a universal requirement: Flutter: Simple app state management.

How do undo and redo work?

Maintain a current state plus two histories: undo states and redo states. For a new legal move, save the current state to undo history, calculate the new state, and clear redo history. Undo saves the current state to redo history and restores the most recent undo state; redo does the reverse. This makes the branch rule explicit: after undoing, making a different move discards the old redo path.

Rank #2
Sale
abxylute M4 Snap-On Mobile Gaming Controller for Android & iPhone, Switch 1&2, Portable Bluetooth Controller, Pocket-Sized Retro Arcade Phone Gamepad Kickstand, Dual Joystick Turbo Pro Gaming Magnetic (Black)
  • Why Choose the abxylute M4 Snap-On Phone Controller? Designed exclusively for short quick retro gaming, like Game Boy, NES, SNES and etc. Trusted by 6000+ backers on a tech-focused crowdfunding platform. Pocket-sized play, perfect for your rest time. This compact clip-on controller is compatible with iOS and Android, features a Turbo function—crafted for short bursts of play vertically, horizontally or in detached mode, and ideal for packing in your pocket.
  • 【Easy Setup – Power On & Play Instantly!】We recommend attaching the magnetic stickers to a phone case for all phones, rather than using a bare phone. ✅ For Apple MagSafe Models: Snap the magnetic ring onto your MagSafe phone case, power on, and start gaming! ✅ For Non‑MagSafe Models: First attach the included magnetic sticker to your phone case, then snap the magnetic ring onto it. Power on and game right away!
  • 【Wide Compatibility – Android & iPhone】Compatible for Android devices, iPhones, and card-size phones (Android devices and iPhone 11/SE and earlier models; iPhone 12/13/14/15/16/17 with MagSafe). Works with all mainstream phones for smooth gaming. Fits iPhone Pro/Pro Max models but may feel top-heavy. Not compatible with foldable phones.
  • 【Compact Yet No Loss of Fun】Featuring HID, PS and NS modes, it seamlessly connects to gaming devices via Bluetooth.⚫ HID Mode: Local Games for Android⚫ PS Mode: CODM & PS Remote Play for Android & iOS⚫ NS Mode: All kinds of Emulators
  • 【Born for Retro Emulators on Mobile】Designed for retro gaming fans, the M4 Controller works smoothly with top emulators such as Delta, RetroArch and PPSSPP on both iOS and Android.It supports classic games for platforms including Game Boy, NES, SNES,3DS, FC, SFC, SS, N64, GBA, GBC, NDS, and more.
class GameController extends ChangeNotifier {
  GameState _state;
  final List<GameState> _undo = [];
  final List<GameState> _redo = [];
  final int maxHistory;

  GameController(this._state, {this.maxHistory = 100}) {
    if (maxHistory < 1) {
      throw ArgumentError.value(maxHistory, 'maxHistory', 'Must be positive');
    }
  }

  GameState get state => _state;
  bool get canUndo => _undo.isNotEmpty;
  bool get canRedo => _redo.isNotEmpty;

  void play(Move move) {
    if (!_state.isLegal(move)) return;
    _undo.add(_state); // GameState snapshots must be immutable.
    if (_undo.length > maxHistory) _undo.removeAt(0);
    _state = _state.apply(move);
    _redo.clear();
    notifyListeners();
  }

  void undo() {
    if (_undo.isEmpty) return;
    _redo.add(_state);
    _state = _undo.removeLast();
    notifyListeners();
  }

  void redo() {
    if (_redo.isEmpty) return;
    _undo.add(_state);
    _state = _redo.removeLast();
    notifyListeners();
  }
}

This sketch is illustrative, not a Flutter-mandated API. It assumes GameState.apply returns a new, independent state rather than mutating a snapshot. In production, also define how reset and new-game actions affect history, whether undo is allowed after a win or loss, and whether the history bound applies to both stacks. The example’s default of 100 is not a recommended universal limit; choose a bound based on the game’s memory needs and the undo experience you want.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Snapshots or reversible move records?

For a compact board game, immutable snapshots are often the simplest representation: each history entry is a complete valid state, so restoring it does not require calculating an inverse move. Their cost grows with both the size of the state and the number of retained entries. The ministate_history package documents this trade-off for its own bounded snapshot history; it is an example, not a Flutter standard or a comparative performance study: pub.dev: ministate_history.

Rank #3
USB Twin Wireless Controller for Retro Game Emulator Gamepad Rechargeable Remote Joystick Joypad for Windows PC,Raspberry Pi,Smart TV/Game Stick/Box, Projector with Emuelec,Batocera‌,Lakka,RetroArch
  • [Powerful Compatibility] - Designed specifically for retro game emulators(Emuelec, Batocera‌, Lakka, RetroArch, Steam, RetroPie), supports only games within the emulator. Support hardware devices: not only for Laptop/Desktop PC(Windows 11/10/8/7/XP, Require: Button Mapping Program), Raspberry Pi(4/3/2/1/Zero), Game Stick(M8/10/15/16), Retro Game Console(Pandora Box Arcade), TV/Game Box, Smart TV, Projector, but also for Android devices(Support OTG Function, Work with OTG Adapter, Not Included), such as Phone, Tablet, Pad. doesn't support for Amazon Firestick/Xbox 360/Xbox One/iOS/Mac OS/PS3/PS4. Please read the product precautions in product description before using them.
  • [Rechargeable Multiuse Wireless Gamepad] - High-performance lithium battery, safe and environmentally friendly, saving your money to buy batteries. intelligent sleep and wake-up functions eff ectively extend the battery life. it's charged quickly through the USB Type-C cable(included). charging time: 2 hours, gaming time: 4+ hours. effortless storage, ready to play anytime.
  • [Gaming Joystick without Delay] - The USB twin wireless emulator controllers adopt 2.4G wireless transmission technology, enjoy seamless 2 player gameplay with a single USB receiver(Included), stable, no delay, perfect for competitive or cooperative gaming sessions. a range of 10 meters(33 feet) covers your living room and bedroom. the controller realizes a wireless connection to your devices, giving you free space to play games. No wires, no mess, no hassle, get rid of wiring and playing games without fear.
  • [Ultimate Game Experience] - Reliable 3D ergonomic design, the design of the left and right shoulder buttons is easier to use and control. compact, lightweight build ideal for kids and adults, reduce hand fatigue during long sessions. the buttons are sensitive and rebound rapidly, leading to your quick moves and high performance in games, bring you a more realistic gaming experience.
  • [Worry-free purchase] - Not only you get a set of USB twin wireless emulator controllers that connect to your devices, but also you will get an unconditional satisfaction guarantee and lifetime warranty. don't hesitate to contact us whenever you need assistance.

A move-record approach stores actions and their inverse operations instead of duplicating a whole state. It can reduce history storage for a large state, but correct undo depends on implementing inverse logic for every relevant change. Commands or events can also make it easier to replay a game for debugging, provided the records contain enough information to reproduce each transition.

Approach History entry Main advantage Main trade-off
Immutable snapshots A complete prior game state Restoration is straightforward; each entry represents a valid state. Memory use grows with state size and retained history length.
Reversible moves or commands A move plus the information needed to reverse or replay it May avoid storing a full state for every move; can support replay and debugging. Inverse logic is more complex and can be incorrect if a transition is not fully reversed.

For either design, decide whether history can be serialized if players should resume a game or replay it later. A move log may be suitable for replay, while persisted progress may require a serializable state, a log, or both. In-memory undo history and saved game progress are separate decisions: Flutter’s state management guidance notes that state can be lost on restart and points readers to platform restoration guidance.

Rank #4
The Learning Journey Early Learning - On The Go Game Controller - Baby Game Controller Toy for Boys & Girls Ages 3 Months and Up - Award Winning Toys
  • KEY FEATURES – Encourage role-play with On the Go Game Controller! Babies and toddlers can now join in the gaming fun with the On the Go Game Controller. Put big fun in your little one’s hands with a game controller that looks like the ones bigger kids use! This controller has multiple buttons, roller balls, and more that play sounds and music and introduce numbers, colors, shapes, and more! Plays delightful melodies, includes a light-up LED, sensory activities, automatic shut-off function, and is battery operated. Requires two “AA” batteries (included). Ages 3+ months.
  • EDUCATIONAL BENEFITS – Promotes listening, visual skills, thinking and learning
  • SUPPORTS DEVELOPMENTAL SKILLS – Stimulates TACTILE/MOTOR SKILLS. Develops ACTION/REACTION SKILLS. Provides hours of interactive learning fun.
  • SAFETY - All Learning Journey products are regularly safety tested and in compliance with all domestic and international toy safety regulations.
  • AWARD WINNING PRODUCTS – Fun fact: The Learning Journey has an extensive line of award winning educational toys that have been tested by the most important panel of judges kids!
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

What does Flutter’s built-in UndoHistory do?

UndoHistory<T> provides undo/redo capabilities for a ValueNotifier. Flutter’s API reference says it “Listens to value and saves relevant values for undoing/redoing.” It also handles keyboard undo/redo shortcuts, calls onTriggered when a shortcut changes the state, and relies on a focus node managed by its child. See Flutter API: UndoHistory<T>.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

This can suit a focused, editable value where platform keyboard shortcuts are useful. It does not know whether a chess move or board-game action is legal, does not define the game’s undo policy, and does not add tap-based undo buttons. Those remain the game controller and UI’s responsibility.

How much history should a game keep?

There is no universal undo depth. Bound history intentionally and choose the limit based on the size of each entry, the device and persistence requirements, and how much backtracking makes sense for the game. Keep only the history the experience requires; for large states, compare the cost of snapshots with the added complexity of reversible records.

  • Clear undo and redo history when starting a new game or resetting, unless the game explicitly supports undoing that transition.
  • After undo followed by a new move, define whether the previous redo branch is discarded; clearing it is the simple, predictable option shown above.
  • Decide whether winning, losing, or leaving a game changes the player’s ability to undo.
  • Keep saved progress separate from transient UI details such as focus or button state.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.