Created
March 5, 2020 12:32
-
-
Save brianegan/9c85f03084be1902f2def2321db02d6d to your computer and use it in GitHub Desktop.
ChageNotifier with Undo/Redo functionality
This file contains hidden or 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 { | |
List<T> _history; | |
int _historyIndex; | |
UndoChangeNotifier([T initialState]) { | |
_history = initialState != null ? [initialState] : []; | |
_historyIndex = initialState != null ? 0 : -1; | |
} | |
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(); | |
notifyListeners(); | |
} | |
} |
This file contains hidden or 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 jump to a state', () { | |
final cn = UndoChangeNotifier('I'); | |
cn.updateState('N'); | |
cn.jumpTo(0); | |
expect(cn.state, 'I'); | |
}); | |
test('can clear the history', () { | |
final cn = UndoChangeNotifier('I'); | |
cn.clear(); | |
expect(cn.state, isNull); | |
}); | |
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