首页 > 解决方案 > Flutter 使用 EditableText

问题描述

我试图弄清楚如何在 Flutter 中使用 TextEditor。

我有“卡片编辑器”(基本上我希望能够处理相当于一段文本)

new EditableText(
                    autofocus: true,
                    maxLines: null,
                    backgroundCursorColor: Colors.amber,
                    cursorColor: Colors.green,
                    style: TextStyle(),
                    focusNode:  FocusNode(),
                    controller: controller,
                    onSubmitted: (val) {
                      _addCard(val);
                      Navigator.pop(context);
                    },
                  )

我从一个 TextField 的例子中改编了这个。

但我有几个问题。

首先,当我输入时,它似乎没有显示任何内容。光标移动,但没有文本可见。当没有明确的风格时,这是默认的吗?

其次,如何触发提交?使用 TextField,CR / Enter 按钮执行此操作。显然我明白为什么你不一定想要 EditableText 但我应该怎么做呢?

第三,我需要能够将默认文本放入这个小部件。我尝试向 EditableText 添加一个“值”属性,但这似乎不对。这样做的方法是什么?

标签: flutterdart

解决方案


  • 来自TextField 类 - 材料库 - Dart API

    EditableText,它是 TextField 核心的原始文本编辑控件。EditableText 小部件很少直接使用,除非您正在实现完全不同的设计语言,例如 Cupertino。

  • 这里是TextField的一个例子,来自我的 app flutter listview CRUD app using nonsecure rest api

    class _TaskEditPageWidgetState extends State<TaskEditPageWidget> {
    TextEditingController _noteController;
    
    @override
    void initState() {
        super.initState();
        _noteController = TextEditingController.fromValue(
        TextEditingValue(
            text: widget.taskOpj.note,
        ),
        );
    }
    
    @override
    void dispose() {
        _noteController.dispose();
        super.dispose();
    }
    
    @override
    Widget build(BuildContext context) {
        return Scaffold(
        appBar: _appBar(),
        body: _body(),
        );
    }
    
    Widget _appBar() {
        return AppBar(
        title: new Text("Edit Task"),
        actions: <Widget>[
            new IconButton(
            icon: new Icon(Icons.save),
            onPressed: _save,
            ),
        ],
        );
    }
    
    Widget _body() {
        return SingleChildScrollView(
        child: Column(
            children: <Widget>[
            Text("Note:"),
            TextField(
                decoration: InputDecoration(border: InputBorder.none),
                autofocus: true,
                keyboardType: TextInputType.multiline,
                maxLines: null,
                controller: _noteController),
            ],
        ),
        );
    }
    
    Future _save() async {
        widget.taskOpj.note = _noteController.text;
        await Tasks.updateTask(widget.taskOpj);
        widget.notifyParent();
        Navigator.pop(context);
    }
    }
    

推荐阅读