Created
March 5, 2020 12:28
-
-
Save brianegan/bad0ea35d8c6f8f25156406bbbd2dfc9 to your computer and use it in GitHub Desktop.
Undo/Redo with ChangeNotifier
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/cupertino.dart'; | |
class UndoChangeNotifier<T> extends ChangeNotifier { | |
final List<T> _history; | |
int _historyIndex = -1; | |
UndoChangeNotifier(T initialState) : _history = [initialState]; | |
T get state => hasState ? _history[_historyIndex] : null; | |
bool get hasState => _history.isNotEmpty; | |
void updateState(T text) { | |
_history.add(text); | |
_historyIndex++; | |
notifyListeners(); | |
} | |
void jumpTo(int index) { | |
_historyIndex = index; | |
notifyListeners(); | |
} | |
void undo() { | |
_historyIndex--; | |
notifyListeners(); | |
} | |
void redo() { | |
_historyIndex++; | |
notifyListeners(); | |
} | |
void clear() { | |
_historyIndex = -1; | |
_history.clear(); | |
} | |
} |
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_test/flutter_test.dart'; | |
import 'package:untitled24/undo_change_notifier.dart'; | |
void main() { | |
group('UndoChangeNotifier', () { | |
test('should start with an initial state', () { | |
final cn = UndoChangeNotifier('I'); | |
expect(cn.state, 'I'); | |
}); | |
test('can update the state', () { | |
final cn = UndoChangeNotifier('I'); | |
cn.updateState('N'); | |
expect(cn.state, 'N'); | |
}); | |
test('can undo a change', () { | |
final cn = UndoChangeNotifier('I'); | |
cn.updateState('N'); | |
cn.undo(); | |
expect(cn.state, 'I'); | |
}); | |
test('can redo a change', () { | |
final cn = UndoChangeNotifier('I'); | |
cn.updateState('N'); | |
cn.undo(); | |
cn.redo(); | |
expect(cn.state, 'N'); | |
}); | |
test('can clear the history', () { | |
final cn = UndoChangeNotifier('I'); | |
cn.clear(); | |
expect(cn.state, isNull); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment