在Flutter中保留方向更改时保留TextField的值

时间:2019-05-20 08:42:45

标签: android ios flutter flutter-layout

我在Flutter的TextField中有一个OrientationBuilder

现在,当我更改App的方向时,发生的事情是TextField的当前值(例如,用户放入其中的文本)丢失了,但是我想保留TextField的值。

我需要重建TextField,因为横向模式下的布局不同。

可以做到吗?

编辑:

这是我到目前为止尝试过的:

我两次都使用以下模型(位于->模型-> markdownModel.dart):

import 'package:scoped_model/scoped_model.dart';

class Code extends Model{
  String _markdown = '# Markdown Preview \n Your Markdown will be rendered here, once you start typing in the editor pane.';

  String get markdown => _markdown;


  void changeMarkdown(String markdown){
    this._markdown = markdown;
    notifyListeners();
  }
}

现在,我第一次尝试执行以下操作(但是请注意,TextField的值未保留在OrientationChange上):

import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';
import 'models/markdownModel.dart';

void main() => runApp(HomeScreen(
      markdown: Code(),
    ));

class HomeScreen extends StatelessWidget {
  final Code markdown;

  const HomeScreen({Key key, this.markdown}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ScopedModel<Code>(
      model: markdown,
      child: MaterialApp(
        home: OrientationBuilder(
          builder: (context, orientation) {
            return orientation == Orientation.portrait
                ? DefaultTabController(
                    initialIndex: 1,
                    length: 2,
                    child: Scaffold(
                      appBar: AppBar(
                        bottom: TabBar(
                          tabs: <Widget>[
                            Tab(text: "Editor", /*icon: Icon(Icons.edit),*/),
                            Tab(text:"Preview", /*icon: Icon(Icons.chrome_reader_mode),*/),
                          ],
                        ),
                        title: Text("Markdown - Editor"),
                        centerTitle: true,
                      ),
                      body: TabBarView(
                        children: <Widget>[
                          TextEditorWidget(),
                          MarkdownPreviewWidget()
                        ],
                      ),
                    ),
                  )
                : Scaffold(
                    appBar: AppBar(
                      title: Text("Markdown - Editor"),
                      centerTitle: true,
                    ),
                    body: Container(
                      child: Row(
                        children: <Widget>[
                          Expanded(
                            child: TextEditorWidget(),
                          ),
                          Expanded(
                            child: MarkdownPreviewWidget(),
                          ),
                        ],
                      ),
                    ),
                  );
          },
        ),
      ),
    );
  }
}

class TextEditorWidget extends StatefulWidget {
  TextEditorWidget({Key key,}) : super(key: key,);

  @override
  _TextEditorWidgetState createState() => _TextEditorWidgetState();
}

class _TextEditorWidgetState extends State<TextEditorWidget> {
  @override
  Widget build(BuildContext context) {
    return ScopedModelDescendant<Code>(builder: (context, child, model) {
      return Container(
        padding: EdgeInsets.all(7.0),
        child: ConstrainedBox(
          constraints: BoxConstraints(
              minWidth: 30, maxWidth: 40, minHeight: 50, maxHeight: 1400),
          child: SingleChildScrollView(
            scrollDirection: Axis.vertical,
            reverse: true,
            child: TextField(
              keyboardType: TextInputType.multiline,
              onChanged: (text){
                model.changeMarkdown(text);
              },
              maxLines: null,
              decoration:
                  InputDecoration.collapsed(hintText: "Write Markdown here."),
            ),
          ),
        ),
      );
    });
  }
}

class MarkdownPreviewWidget extends StatefulWidget {
  MarkdownPreviewWidget({Key key,}) : super(key: key,);

  @override
  _MarkdownPreviewWidgetState createState() => _MarkdownPreviewWidgetState();
}

class _MarkdownPreviewWidgetState extends State<MarkdownPreviewWidget> {
  @override
  Widget build(BuildContext context) {
    return ScopedModelDescendant<Code>(builder: (context, child, model) {
      return Container(
        child: new Markdown(
          data: model.markdown,
        ),
      );
    });
  }
}

然后,正如乔治指出的那样,我在TextEditingController的构建方法之外使用了OrientationBuilder。这行得通(在我的情况下,需要一些额外的技巧),但是应用程序现在异常缓慢:

import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';
import 'models/markdownModel.dart';

void main() => runApp(HomeScreen(
      markdown: Code(),
    ));

class HomeScreen extends StatelessWidget {
  final Code markdown;

  const HomeScreen({Key key, this.markdown}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ScopedModel<Code>(
      model: markdown,
      child: MaterialApp(
        home: MainView(),
      ),
    );
  }
}

class MainView extends StatefulWidget {
  MainView({Key key,}) : super(key: key,);

  @override
  _MainViewState createState() => _MainViewState();
}

class _MainViewState extends State<MainView> {
  final _textController = TextEditingController();

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    // Clean up the controller when the Widget is removed from the Widget tree
    // This also removes the _printLatestValue listener
    _textController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return OrientationBuilder(
          builder: (context, orientation) {
            return orientation == Orientation.portrait
                ? DefaultTabController(
                    initialIndex: 1,
                    length: 2,
                    child: Scaffold(
                      appBar: AppBar(
                        bottom: TabBar(
                          tabs: <Widget>[
                            Tab(text: "Editor", /*icon: Icon(Icons.edit),*/),
                            Tab(text:"Preview", /*icon: Icon(Icons.chrome_reader_mode),*/),
                          ],
                        ),
                        title: Text("Markdown - Editor"),
                        centerTitle: true,
                      ),
                      body: TabBarView(
                        children: <Widget>[
                          TextEditorWidget(textController: _textController,),
                          MarkdownPreviewWidget()
                        ],
                      ),
                    ),
                  )
                : Scaffold(
                    appBar: AppBar(
                      title: Text("Markdown - Editor"),
                      centerTitle: true,
                    ),
                    body: Container(
                      child: Row(
                        children: <Widget>[
                          Expanded(
                            child: TextEditorWidget(textController: _textController,),
                          ),
                          Expanded(
                            child: MarkdownPreviewWidget(),
                          ),
                        ],
                      ),
                    ),
                  );
          });
  }
}


class TextEditorWidget extends StatefulWidget {
  final textController;
  TextEditorWidget({Key key, @required this.textController }) : super(key: key,);

  @override
  _TextEditorWidgetState createState() => _TextEditorWidgetState();
}

class _TextEditorWidgetState extends State<TextEditorWidget> {
  @override
  Widget build(BuildContext context) {
    return ScopedModelDescendant<Code>(builder: (context, child, model) {
      widget.textController.addListener(
        model.changeMarkdown(widget.textController.text)
      );
      return Container(
        padding: EdgeInsets.all(7.0),
        child: ConstrainedBox(
          constraints: BoxConstraints(
              minWidth: 30, maxWidth: 40, minHeight: 50, maxHeight: 1400),
          child: SingleChildScrollView(
            scrollDirection: Axis.vertical,
            reverse: true,
            child: TextField(
              keyboardType: TextInputType.multiline,
              controller: widget.textController,
              maxLines: null,
              decoration:
                  InputDecoration.collapsed(hintText: "Write Markdown here."),
            ),
          ),
        ),
      );
    });
  }
}

class MarkdownPreviewWidget extends StatefulWidget {
  MarkdownPreviewWidget({Key key,}) : super(key: key,);

  @override
  _MarkdownPreviewWidgetState createState() => _MarkdownPreviewWidgetState();
}

class _MarkdownPreviewWidgetState extends State<MarkdownPreviewWidget> {
  @override
  Widget build(BuildContext context) {
    return ScopedModelDescendant<Code>(builder: (context, child, model) {
      return Container(
        child: new Markdown(
          data: model.markdown,
        ),
      );
    });
  }
}

编辑2:

我认为上面的示例很慢,因为一遍又一遍地抛出以下异常:

I/flutter ( 5375): ══╡ EXCEPTION CAUGHT BY FOUNDATION LIBRARY 

╞════════════════════════════════════════════════════════
I/flutter ( 5375): The following NoSuchMethodError was thrown while dispatching notifications for
I/flutter ( 5375): TextEditingController:
I/flutter ( 5375): The method 'call' was called on null.
I/flutter ( 5375): Receiver: null
I/flutter ( 5375): Tried calling: call()
I/flutter ( 5375):
I/flutter ( 5375): When the exception was thrown, this was the stack:
I/flutter ( 5375): #0      Object.noSuchMethod  (dart:core-patch/object_patch.dart:50:5)
I/flutter ( 5375): #1      ChangeNotifier.notifyListeners 
package:flutter/…/foundation/change_notifier.dart:206
I/flutter ( 5375): #2      ValueNotifier.value= 
package:flutter/…/foundation/change_notifier.dart:270
I/flutter ( 5375): #3      TextEditingController.selection= 
package:flutter/…/widgets/editable_text.dart:166
I/flutter ( 5375): #4      EditableTextState._handleSelectionChanged 
package:flutter/…/widgets/editable_text.dart:1118
I/flutter ( 5375): #5      RenderEditable.selectPositionAt 
package:flutter/…/rendering/editable.dart:1403
I/flutter ( 5375): #6      RenderEditable.selectPosition 
package:flutter/…/rendering/editable.dart:1375
I/flutter ( 5375): #7      _TextFieldState._handleSingleTapUp 
package:flutter/…/material/text_field.dart:686
I/flutter ( 5375): #8      _TextSelectionGestureDetectorState._handleTapUp 
package:flutter/…/widgets/text_selection.dart:806
I/flutter ( 5375): #9      TapGestureRecognizer._checkUp.<anonymous closure> 
package:flutter/…/gestures/tap.dart:238
I/flutter ( 5375): #10     GestureRecognizer.invokeCallback 
package:flutter/…/gestures/recognizer.dart:166
I/flutter ( 5375): #11     TapGestureRecognizer._checkUp 
package:flutter/…/gestures/tap.dart:238
I/flutter ( 5375): #12     TapGestureRecognizer.acceptGesture 
package:flutter/…/gestures/tap.dart:211
I/flutter ( 5375): #13     GestureArenaManager.sweep 
package:flutter/…/gestures/arena.dart:156
I/flutter ( 5375): #14     _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent 
package:flutter/…/gestures/binding.dart:225
I/flutter ( 5375): #15     _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent 
package:flutter/…/gestures/binding.dart:199
I/flutter ( 5375): #16     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent 
package:flutter/…/gestures/binding.dart:156
I/flutter ( 5375): #17     _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue 
package:flutter/…/gestures/binding.dart:102
I/flutter ( 5375): #18     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket 
package:flutter/…/gestures/binding.dart:86
I/flutter ( 5375): #22     _invoke1  (dart:ui/hooks.dart:233:10)
I/flutter ( 5375): #23     _dispatchPointerDataPacket  (dart:ui/hooks.dart:154:5)
I/flutter ( 5375): (elided 3 frames from package dart:async)
I/flutter ( 5375):
I/flutter ( 5375): The TextEditingController sending notification was:
I/flutter ( 5375):   TextEditingController#05f71(TextEditingValue(text: ┤├, selection: TextSelection(baseOffset: 0,
I/flutter ( 5375):   extentOffset: 0, affinity: TextAffinity.downstream, isDirectional: false), composing:
I/flutter ( 5375):   TextRange(start: -1, end: -1)))
I/flutter ( 5375): ════════════════════════════════════════════════════════════════════════════════════════════════════
I/flutter ( 5375): Another exception was thrown: NoSuchMethodError: The method 'call' was called on null.
I/chatty  ( 5375): uid=10098(com.example.markdown_editor) Thread-2 identical 42 lines
I/flutter ( 5375): Another exception was thrown: NoSuchMethodError: The method 'call' was called on null.
I/flutter ( 5375): Another exception was thrown: NoSuchMethodError: The method 'call' was called on null.
I/chatty  ( 5375): uid=10098(com.example.markdown_editor) Thread-2 identical 7 lines

顺便说一句。我正在尝试使用实时预览构建一个简单的markdown编辑器...

2 个答案:

答案 0 :(得分:1)

发生这种情况的原因: OrientationBuilder会在方向更改时重新构建自身,可能会重置其中所有小部件的状态。

解决方案:为您的TextEditingController分配一个TextField,并在OrientationBuilder上下文之外声明控制器。这样可以防止文本字段丢失其值。

例如

final _controller = TextEditingController();

Widget build(BuildContext context) {
  // ...
    TextField(
      controller: _controller,
    )
  // ...
}

编辑,感谢您提供的代码。

首先,更改此:

class _TextEditorWidgetState extends State<TextEditorWidget> {
  @override
  Widget build(BuildContext context) {
    return ScopedModelDescendant<Code>(builder: (context, child, model) {
      widget.textController.addListener(
        model.changeMarkdown(widget.textController.text)
      );
// ...

对此:

class _TextEditorWidgetState extends State<TextEditorWidget> {

  @override
  void initState() {
    super.initState();
    widget.textController.addListener(controllerListener);
  }

  @override
  void dispose() {
    widget.textController.removeListener(controllerListener);
    super.dispose();
  }

  void controllerListener() {
    // I'm not entirely sure what `changeMarkdown` method does exactly in your code.
    // If this does not work - ask a separate question about scoped models.
    ScopedModel.of<Code>(context).changeMarkdown(widget.textController.text);
  }

  @override
  Widget build(BuildContext context) {
    return ScopedModelDescendant<Code>(builder: (context, child, model) {

  // ...
}

还有一件小事-在Row中考虑用Expanded替换Flexible

希望这会有所帮助。

答案 1 :(得分:1)

很抱歉,@ George方法是正确的,但简单的方法是通过在小部件中使用键来实现此目的,只需在TextField小部件中添加键字段并在State Class中添加final _inputKey = GlobalKey(debugLabel: 'inputText');即可保留文本字段方向改变的价值