Flutter 组件集录 | 后悔药 UndoHistory
在Flutter中,UndoHistory
是一个用于处理撤销操作的类。它通常不是直接使用的,而是作为Undo
包中其他控件的一部分,如UndoStack
。如果你需要实现一个简单的撤销功能,你可以使用ValueNotifier
和ValueListenableBuilder
来创建一个简单的撤销控件。
以下是一个简单的例子,展示了如何使用ValueNotifier
和ValueListenableBuilder
来创建一个简单的撤销记录系统:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final _undoHistory = UndoHistory<String>();
void _addItem(String item) {
_undoHistory.add(item);
}
void _undo() {
_undoHistory.undo();
}
void _redo() {
_undoHistory.redo();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ValueListenableBuilder<List<String>>(
valueListenable: _undoHistory.undoStack,
builder: (context, stack, child) {
return Text('Undo Stack: ${stack.join(", ")}');
},
),
ValueListenableBuilder<List<String>>(
valueListenable: _undoHistory.redoStack,
builder: (context, stack, child) {
return Text('Redo Stack: ${stack.join(", ")}');
},
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FlatButton(
child: Text('Add Item'),
onPressed: () => _addItem('Item'),
),
FlatButton(
child: Text('Undo'),
onPressed: _undoHistory.canUndo ? _undo : null,
),
FlatButton(
child: Text('Redo'),
onPressed: _undoHistory.canRedo ? _redo : null,
),
],
),
],
),
),
);
}
}
class UndoHistory<T> {
final _undoStack = <T>[];
final _redoStack = <T>[];
final ValueNotifier<List<T>> _undoStackNotifier = ValueNotifier([]);
final ValueNotifier<List<T>> _redoStackNotifier = ValueNotifier([]);
ValueListenable<List<T>> get undoStack =>
评论已关闭