Flutter-弹出模式导航器后设置controller.text不起作用

时间:2019-07-15 06:40:19

标签: flutter dart

工作目标:

我正在处理一个输入字段小部件,它将弹出一个模态供用户按下时选择选项,并在模态关闭后在小部件上显示所选选项。

代码

输入字段小部件

import 'package:flutter/material.dart';
import 'package:travfolk_app/screens/modals/search.dart';

class SearchSelectField extends StatefulWidget {
  SearchSelectField({
    this.onSaved
  }): super();

  Function onSaved;
  TextEditingController controller = TextEditingController();

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

class _SearchSelectFieldState extends State<SearchSelectField> {
  @override
  Widget build(BuildContext context) {
    return FormField(
      builder: (state) {
        return InkWell(
          onTap: openKeywordFieldModal,
          child: TextField(
            enabled: false,
            controller: widget.controller,
            decoration: InputDecoration(
              labelText: 'Placeholder'
            )
          ),
        );
      }
    );
  }

  void openKeywordFieldModal () {
    Navigator.push(context,
      MaterialPageRoute(
        fullscreenDialog: true,
        builder: (context) => SearchModalScreen()
      )
    ).then((option) {
      if (option != '') {
        print("outside setState" + option.toString());
        setState(() {
          print("inside setState" + option.toString());
          widget.controller.text = option.toString();
        });
      }
    });
  }

  @override
  void dispose() {
    widget.controller.dispose();
    super.dispose();
  }
}

搜索模式屏幕

import 'package:flutter/material.dart';

class SearchModalScreen extends StatefulWidget {
  @override
  _SearchModalScreenState createState() => _SearchModalScreenState();
}

class _SearchModalScreenState extends State<SearchModalScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Column(
          children: <Widget>[
            FlatButton(
              onPressed: () => chooseOption('answer 1'),
              child: Text('answer 1')
            )
          ]
        )
      )
    );
  }

  void chooseOption(String value) {
    Navigator.of(context).pop(value);
  }
}

遇到的问题:

在取消模态后,窗口小部件无法显示“答案1”,而这两个print()函数正常工作以在终端中显示“答案1”。感谢您的帮助。

0 个答案:

没有答案