Flutter TextEditingController保留值,而无需点击完成按钮

时间:2019-12-18 07:44:12

标签: flutter

简单的添加地点小部件

  • 标题文本字段
  • 容器-从相机渲染图像
  • 按钮-激活摄像头设备

我认为将一个控制器连接到TextField会自动保存输入值的状态。但是,从我的示例中,如果我输入文本时未单击“完成”,然后立即单击“拍摄照片”按钮。从摄像机操作返回后,将清除TextField输入值。

如何重现问题:

  1. 在字段中输入文字
  2. 立即单击“相机”按钮,而无需单击完成/检查或按键盘上的Enter键
  3. 拍照确认。
  4. 返回页面TextField为空

示例代码:

AddPlacePage StatefulWidget

Column(
              children: <Widget>[
                TextField(
                  decoration: InputDecoration(labelText: 'Title'),
                  controller: _titleController,
                ),

                ImageInput(),
              ],
            ),

ImageInput StatefulWidget

  class _ImageInputState extends State<ImageInput> {
  File _storedImage;

  Future<void> _takePicture() async {
    final imageFile = await ImagePicker.pickImage(
      source: ImageSource.camera,
      maxWidth: 600,
    );
    setState(() {
      _storedImage = imageFile;
    });
    ...
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: <Widget>[
        Container(
          ...
          child: _storedImage != null
              ? Image.file(
                  _storedImage,
                  fit: BoxFit.cover,
                  width: double.infinity,
                )
              : Text(
                  'No Image Taken',
                  textAlign: TextAlign.center,
                ),
          alignment: Alignment.center,
        ),

        Expanded(
          child: FlatButton.icon(
            icon: Icon(Icons.camera),
            label: Text('Take Picture'),
            textColor: Theme.of(context).primaryColor,
            onPressed: () => _takePicture(),
          ),
        ),
      ],
    );
  }
}

问题:

即使退出应用程序访问设备摄像头后,如何修改TextField的控制器以保留输入值?

TextField(
  decoration: InputDecoration(labelText: 'Title'),
  controller: _titleController,
),

我确实尝试创建一个局部变量并尝试使用onChange:

   String _inputValue

   build(BuildContext context){

     ...   
     TextField(
        decoration: InputDecoration(labelText: 'Title'),
        controller: _titleController,
        onChange: (value) => _inputValue = value;
     ),          

但是,从Flutter重新调出页面后,从相机返回的效果是相同的,_inputValue和_titleController.text均被清除。

示例代码: https://github.com/erich5168/flutter_camera_example

1 个答案:

答案 0 :(得分:0)

您可以使用share preferences将字符串保存到设备,然后在返回文本字段时调用它。这就是我的实现方式:

class LocalStorage {
  static SharedPreferences instance;

  static Future init() async {
    instance = await SharedPreferences.getInstance();
  }

  static dynamic getValue(String key, dynamic emptyValue) {
    if (LocalStorage.instance.containsKey(key)) {
      return LocalStorage.instance.get(key);
    }
    return emptyValue;
  }
}

将其设置为文本字段:

TextEditingController _usernameController =
  new TextEditingController(text: LocalStorage.getValue('UserName', ''));
相关问题