我有一个MaterialApp,它具有导航到不同小部件的不同路线。
现在让我们假设路线“ / search”的小部件具有搜索输入字段。
如果我现在替换导航到“ / foo”并返回到“ / search”,则由于“ / search”后面的小部件是从头开始构建的,因此搜索输入字段的内容将丢失。
什么是正确的“教条式”颤动方法,以使文本编辑字段的内容可能消失并重新出现?
答案 0 :(得分:0)
基本上,没有“教条”的方式来保持状态的平稳。您有不同的选择,然后选择最适合您的需求。 有ScopedModel,BLoC,Redux等。 我建议您观看talk,了解不同的状态管理工具和方法。
答案 1 :(得分:0)
这是我来到的解决方案。它将围绕TextField创建一个包装器小部件,该小部件可处理TextField值向PageStore的读写。
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class StoredTextField extends StatelessWidget {
final TextField child;
StoredTextField(
{@required PageStorageKey key,
String initialValue,
FocusNode focusNode,
InputDecoration decoration = const InputDecoration(),
TextInputType keyboardType,
TextInputAction textInputAction,
TextCapitalization textCapitalization = TextCapitalization.none,
TextStyle style,
TextAlign textAlign = TextAlign.start,
TextDirection textDirection,
bool autofocus = false,
bool obscureText = false,
bool autocorrect = true,
int maxLines = 1,
int maxLength,
bool maxLengthEnforced = true,
ValueChanged<String> onChanged,
VoidCallback onEditingComplete,
ValueChanged<String> onSubmitted,
List<TextInputFormatter> inputFormatters,
bool enabled,
double cursorWidth = 2.0,
Radius cursorRadius,
Color cursorColor,
Brightness keyboardAppearance,
EdgeInsets scrollPadding = const EdgeInsets.all(20.0),
DragStartBehavior dragStartBehavior = DragStartBehavior.down,
bool enableInteractiveSelection,
GestureTapCallback onTap,
InputCounterWidgetBuilder buildCounter})
: child = TextField(
key: PageStorageKey(
"child"), // TextField has its own stored state, so pass a PageStorageKey
controller: TextEditingController(text: initialValue),
focusNode: focusNode,
decoration: decoration,
keyboardType: keyboardType,
textInputAction: textInputAction,
textCapitalization: textCapitalization,
style: style,
textAlign: textAlign,
textDirection: textDirection,
autofocus: autofocus,
obscureText: obscureText,
autocorrect: autocorrect,
maxLines: maxLines,
maxLength: maxLength,
maxLengthEnforced: maxLengthEnforced,
onChanged: onChanged,
onEditingComplete: onEditingComplete,
onSubmitted: onSubmitted,
enabled: enabled,
cursorWidth: cursorWidth,
cursorColor: cursorColor,
keyboardAppearance: keyboardAppearance,
scrollPadding: scrollPadding,
dragStartBehavior: dragStartBehavior,
enableInteractiveSelection: enableInteractiveSelection,
onTap: onTap,
buildCounter: buildCounter),
super(key: key);
@override
Widget build(BuildContext context) {
final controller = child.controller;
final storage = PageStorage.of(context);
final value = storage?.readState(context);
if (value is String) {
controller.text = value;
}
controller.addListener(() {
storage?.writeState(context, controller.text);
});
return child;
}
}