Flutter的TextField,虽然能通过下面的形式输入多行内容,但是感觉很不舒服并且功能很单一。
1 2 3 4 |
child: new TextField( keyboardType: TextInputType.multiline, maxLines: null, ) |
所以我们需要一个富文本框,我们需要一个Flutter插件。
https://pub.dev/packages/zefyr#-readme-tab-
https://zefyr-editor.gitbook.io/docs/quick-start
首先来安装它
pubspec.yaml中添加
1 2 |
dependencies: zefyr: ^0.8.0 |
安装
1 |
flutter pub get |
现在我们来使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
import 'dart:convert'; import 'package:flutter/material.dart'; //富文本框 import 'package:zefyr/zefyr.dart'; import 'package:quill_delta/quill_delta.dart'; class AddProduct extends StatefulWidget{ AddProduct({Key key}) : super(key: key); final String title = "添加页面"; @override State<StatefulWidget> createState() { // TODO: implement createState return _AddProductState(); } } class _AddProductState extends State<AddProduct> { /// //富文本框Allows to control the editor and the document. ZefyrController _controller; /// //富文本框Zefyr editor like any other input field requires a focus node. FocusNode _focusNode; @override void initState() { super.initState(); // //富文本框Here we must load the document and pass it to Zefyr controller. final document = _loadDocument(); _controller = ZefyrController(document); _focusNode = FocusNode(); } @override Widget build(BuildContext context) { // TODO: implement build return Scaffold( appBar: AppBar( title: Text(widget.title), // <<< begin change actions: <Widget>[ Builder( builder: (context) => IconButton( icon: Icon(Icons.save), onPressed: () => _saveDocument(context), ), ) ], // end change >>> ), body: WillPopScope( child: ZefyrScaffold( /*child: new TextField( keyboardType: TextInputType.multiline, maxLines: null, ),*/ //富文本框 child: ZefyrEditor( padding: EdgeInsets.all(16), controller: _controller, focusNode: _focusNode, ), ), //监听返回按钮被触发 onWillPop: () async{ print("返回键点击了"); return true; }, ) ); } ///富文本框加载内容方法 /// Loads the document to be edited in Zefyr. NotusDocument _loadDocument() { // For simplicity we hardcode a simple document with one line of text // saying "Zefyr Quick Start". // (Note that delta must always end with newline.)这里一定要有\n final Delta delta = Delta()..insert("\n"); return NotusDocument.fromDelta(delta); } /// 保存内容方法 void _saveDocument(BuildContext context) { // Notus documents can be easily serialized to JSON by passing to // `jsonEncode` directly final contents = jsonEncode(_controller.document); // For this example we save our document to a temporary file. print(contents); } } |