Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD

flutter html editor – enhanced

flutter html editor enhanced is a text editor for android, ios, and web to help write wysiwyg html code with the summernote javascript wrapper.

note that the api shown in this readme.md file shows only a part of the documentation and, also, conforms to the github master branch only! so, here you could have methods, options, and events that aren’t published/released yet! if you need a specific version, please change the github branch of this repository to your version or use the online api reference (recommended).

video example light mode and

toolbartype.nativegrid
dark mode and

toolbarposition.beloweditor
gif example light dark
flutter web
flutter web

setup

add html_editor_enhanced: ^2.1.1 as dependency to your pubspec.yaml.

additional setup is required on ios to allow the user to pick files from storage. see here for more details.

for images, the package uses filetype.image, for video filetype.video, for audio filetype.audio, and for any other file filetype.any. you can just complete setup for the specific buttons you plan to enable in the editor.

v2.0.0 migration guide:

migration guide

basic usage

import 'package:html_editor/html_editor.dart';

htmleditorcontroller controller = htmleditorcontroller();

@override widget build(buildcontext context) {
    return htmleditor(
        controller: controller, //required
        htmleditoroptions: htmleditoroptions(
          hint: "your text here...",
          //initaltext: "text content initial, if any",
        ),   
        otheroptions: otheroptions(
          height: 400,
        ),
    );
}

important note for web:

at the moment, there is quite a bit of flickering and repainting when having many ui elements draw over iframeelements. see https://github.com/flutter/flutter/issues/71888 for more details.

the current workaround is to build and/or run your web app with flutter run --web-renderer html and flutter build web --web-renderer html.

follow https://github.com/flutter/flutter/issues/80524 for updates on a potential fix, in the meantime the above solution should resolve the majority of the flickering issues.

important note about toolbar buttons:

it is highly recommended to pick and choose which buttons you’d like to show – pretty much every single button is shown by default, and this might be overwhelming for users. you can do this like so:

import 'package:html_editor/html_editor.dart';

htmleditorcontroller controller = htmleditorcontroller();

@override widget build(buildcontext context) {
    return htmleditor(
        controller: controller, //required
        htmleditoroptions: htmleditoroptions(
          hint: "your text here...",
          //initaltext: "text content initial, if any",
        ),   
        htmltoolbaroptions: htmltoolbaroptions(
          defaulttoolbarbuttons: [
            //add constructors here and set buttons to false, e.g.
            paragraphbuttons(lineheight: false, caseconverter: false)
          ]
        ),   
        otheroptions: otheroptions(
          height: 400,
        ),
    );
}

please note: you cannot just add the constructor of the button group you’d like to remove buttons from. if you do this, then the plugin will only show buttons from that specific button group. you must add all the other constructors in, and you can leave them blank: [listbuttons(), paragraphbuttons()] etc.

more details available below

when you want to get text from the editor:

final txt = await controller.gettext();

api reference

for the full api reference, see here.

for a full example, see here.

below, you will find brief descriptions of the parameters the htmleditor widget accepts and some code snippets to help you use this package.

parameters – htmleditor

parameter type default description
controller htmleditorcontroller empty required param. create a controller instance and pass it to the widget. this ensures that any methods called work only on their htmleditor instance, allowing you to use multiple html widgets on one page.
callbacks callbacks empty customize the callbacks for various events
options htmleditoroptions htmleditoroptions() class to set various options. see below for more details.
plugins list<plugins> empty customize what plugins are activated. see below for more details.
toolbar list<toolbar> see the widget’s constructor customize what buttons are shown on the toolbar, and in which order. see below for more details.

parameters – htmleditorcontroller

parameter type default description
processinputhtml bool true determines whether processing occurs on any input html (e.g. escape quotes, apostrophes, and remove /ns)
processnewlineasbr bool false determines whether a new line (n) becomes a <br/> in any input html
processoutputhtml bool true determines whether processing occurs on any output html (e.g. <p><br/><p> becomes "")

parameters – htmleditoroptions

parameter type default description
autoadjustheight bool true automatically adjust the height of the text editor by analyzing the html height once the editor is loaded. recommended value: true. see below for more details.
adjustheightforkeyboard bool true adjust the height of the editor if the keyboard is active and it overlaps the editor to prevent the overlap. recommended value: true, only works on mobile. see below for more details.
darkmode bool null sets the status of dark mode – false: always light, null: follow system, true: always dark
filepath string null allows you to specify your own html to be loaded into the webview. you can create a custom page with summernote, or theoretically load any other editor/html.
hint string empty placeholder hint text
initialtext string empty initial text content for text editor
mobilecontextmenu contextmenu null customize the context menu when a user selects text in the editor. see docs for contextmenu here
mobilelongpressduration duration duration(milliseconds: 500) set the duration until a long-press is recognized
mobileinitialscripts unmodifiablelistview<userscript> null easily inject scripts to perform actions like changing the background color of the editor. see docs for userscript here
shouldensurevisible bool false scroll the parent scrollable to the top of the editor widget when the webview is focused. do not use this parameter if htmleditor is not inside a scrollable. see below for more details.

parameters – htmltoolbaroptions

toolbar options

parameter type default description
audioextensions list<string> null allowed extensions when inserting audio files
customtoolbarbuttons list<widget> empty add custom buttons to the toolbar
customtoolbarinsertionindices list<int> empty allows you to set where each custom toolbar button should be inserted into the toolbar widget list
defaulttoolbarbuttons list<toolbar> (all constructors active) allows you to hide/show certain buttons or certain groups of buttons
otherfileextensions list<string> null allowed extensions when inserting files other than image/audio/video
imageextensions list<string> null allowed extensions when inserting images
linkinsertinterceptor futureor<bool> function(string, string, bool) null intercept any links inserted into the editor. the function passes the display text, the url, and whether it opens a new tab.
medialinkinsertinterceptor futureor<bool> function(string, insertfiletype) null intercept any media links inserted into the editor. the function passes the url and insertfiletype which indicates which file type was inserted
mediauploadinterceptor futureor<bool> function(platformfile, insertfiletype) null intercept any media files inserted into the editor. the function passes platformfile which holds all relevant file data, and insertfiletype which indicates which file type was inserted.
onbuttonpressed futureor<bool> function(buttontype, bool?, void function()?) null intercept any button presses. the function passes the enum for the pressed button, the current selected status of the button (if applicable) and a function to update the status (if applicable).
ondropdownchanged futureor<bool> function(dropdowntype, dynamic, void function(dynamic)?) null intercept any dropdown changes. the function passes the enum for the changed dropdown, the changed value, and a function to update the changed value (if applicable).
onotherfilelinkinsert function(string) null intercept file link inserts other than image/audio/video. this handler is required when using the other file button, as the package has no built-in handlers
onotherfileupload function(platformfile) null intercept file uploads other than image/audio/video. this handler is required when using the other file button, as the package has no built-in handlers
otherfileextensions list<string> null allowed extensions when inserting files other than image/audio/video
toolbartype toolbartype toolbartype.nativescrollable customize how the toolbar is displayed (gridview or scrollable)
toolbarposition toolbarposition toolbarposition.aboveeditor set where the toolbar is displayed (above or below the editor)
videoextensions list<string> null allowed extensions when inserting videos

styling options

parameter type default description
renderborder bool false render a border around dropdowns and buttons
textstyle textstyle null the textstyle to use when displaying dropdowns and buttons
separatorwidget widget verticaldivider(indent: 2, endindent: 2, color: colors.grey) set the widget that separates each group of buttons/dropdowns
renderseparatorwidget bool true whether or not the separator widget should be rendered
toolbaritemheight double 36 set the height of dropdowns and buttons. buttons will maintain a square aspect ratio.
gridviewhorizontalspacing double 5 the horizontal spacing to use between button groups when displaying the toolbar as toolbartype.nativegrid
gridviewverticalspacing double 5 the vertical spacing to use between button groups when diplaying the toolbar as toolbartype.nativegrid

styling options – applies to dropdowns only

parameter type default
dropdownelevation int 8
dropdownicon widget null
dropdowniconcolor color null
dropdowniconsize double 24
dropdownitemheight double kmininteractivedimension (48)
dropdownfocuscolor color null
dropdownbackgroundcolor color null
dropdownmenudirection dropdownmenudirection null
dropdownmenumaxheight double null
dropdownboxdecoration boxdecoration null

styling options – applies to buttons only

parameter type default
buttoncolor color null
buttonselectedcolor color null
buttonfillcolor color null
buttonfocuscolor color null
buttonhighlightcolor color null
buttonhovercolor color null
buttonsplashcolor color null
buttonbordercolor color null
buttonselectedbordercolor color null
buttonborderradius borderradius null
buttonborderwidth double null

parameters – other options

parameter type default description
decoration boxdecoration null boxdecoration that surrounds the widget
height double null height of the widget (includes toolbar and editing area)

methods

access these methods like this: <controller name>.<method name>

method argument(s) returned value(s) description
addnotification() string html, notificationtype notificationtype n/a adds a notification to the bottom of the editor with the provided html content. notificationtype determines how it is styled.
clear() n/a n/a resets the html editor to its default state
clearfocus() n/a n/a clears focus for the webview and resets the height to the original height on mobile. do not use this method in flutter web.
disable() n/a n/a disables the editor (a gray mask is applied and all touches are absorbed)
enable() n/a n/a enables the editor
execcommand() string command, string argument (optional) n/a allows you to run any execcommand command easily. see the mdn docs for usage.
gettext() n/a future<string> returns the current html in the editor
inserthtml() string n/a inserts the provided html string into the editor at the current cursor position. do not use this method for plaintext strings.
insertlink() string text, string url, bool isnewwindow n/a inserts a hyperlink using the provided text and url into the editor at the current cursor position. isnewwindow defines whether a new browser window is launched if the link is tapped.
insertnetworkimage() string url, string filename (optional) n/a inserts an image using the provided url and optional filename into the editor at the current cursor position. the image must be accessible via a url.
inserttext() string n/a inserts the provided text into the editor at the current cursor position. do not use this method for html strings.
recalculateheight() n/a n/a recalculates the height of the editor by re-evaluating document.body.scrollheight
redo() n/a n/a redoes the last command in the editor
reloadweb() n/a n/a reloads the webpage in flutter web. this is mainly provided to refresh the text editor theme when the theme is changed. do not use this method in flutter mobile.
removenotification() n/a n/a removes the current notification from the bottom of the editor
resetheight() n/a n/a resets the height of the webview to the original height. do not use this method in flutter web.
sethint() string n/a sets the current hint text of the editor
setfocus() n/a n/a if the pointer is in the webview, the focus will be set to the editor box
setfullscreen() n/a n/a sets the editor to take up the entire size of the webview
settext() string n/a sets the current text in the html to the input html string
togglecodeview() n/a n/a toggles between the code view and the rich text view
undo() n/a n/a undoes the last command in the editor

callbacks

every callback is defined as a function(<parameters in some cases>). see the documentation for more specific details on each callback.

callback parameter(s) description
onbeforecommand string called before certain commands are called (like undo and redo), passes the html in the editor before the command is called
onchangecontent string called when the content of the editor changes, passes the current html in the editor
onchangecodeview string called when the content of the codeview changes, passes the current code in the codeview
onchangeselection editorsettings called when the current selection of the editor changes, passes all editor settings (e.g. bold/italic/underline, color, text direction, etc).
ondialogshown n/a called when either the image, link, video, or help dialogs are shown
onenter n/a called when enter/return is pressed
onfocus n/a called when the rich text field gains focus
onblur n/a called when the rich text field or the codeview loses focus
onblurcodeview n/a called when the codeview either gains or loses focus
onimagelinkinsert string called when an image is inserted via url, passes the url of the image
onimageupload fileupload called when an image is inserted via upload, passes fileupload which holds filename, date modified, size, and mime type
onimageuploaderror fileupload, string, uploaderror called when an image fails to inserted via upload, passes fileupload which may hold filename, date modified, size, and mime type (or be null), string which is the base64 (or null), and uploaderror which describes the type of error
oninit n/a called when the rich text field is initialized and javascript methods can be called
onkeydown int called when a key is downed, passes the keycode of the downed key
onkeyup int called when a key is released, passes the keycode of the released key
onmousedown n/a called when the mouse/finger is downed
onmouseup n/a called when the mouse/finger is released
onpaste n/a called when content is pasted into the editor
onscroll n/a called when editor box is scrolled

getters

currently, the package has one getter: <controller name>.editorcontroller. this returns the inappwebviewcontroller, which manages the webview that displays the editor.

this is extremely powerful, as it allows you to create your own custom methods and implementations directly in your app. see flutter_inappwebview for documentation on the controller.

this getter should not be used in flutter web. if you are making a cross platform implementation, please use kisweb to check the current platform in your code.

toolbar

this api allows you to customize the toolbar in a nice, readable format.

by default, the toolbar will have all buttons enabled except the “other file” button, because the plugin cannot handle those files out of the box.

here’s what that a custom implementation could look like:

htmleditorcontroller controller = htmleditorcontroller();
widget htmleditor = htmleditor(
  controller: controller, //required
  //other options
  toolbaroptions: htmltoolbaroptions(
    defaulttoolbarbuttons: [
        stylebuttons(),
        paragraphbuttons(lineheight: false, caseconverter: false)
    ]
  )
);

if you leave the toolbar constructor blank (like style() above), then the package interprets that you want all the buttons for the style group to be visible.

if you want to remove certain buttons from the group, you can set their button name to false, as shown in the example above.

order matters! whatever group you set first will be the first group of buttons to display.

if you don’t want to show an entire group of buttons, simply don’t include their constructor in the toolbar list! this means that if you want to disable just one button, you still have to provide all other constructors.

you can also create your own toolbar buttons! see below for more details.

plugins

this api allows you to add certain summernote plugins from the summernote awesome library.

currently the following plugins are supported:

  1. summernote case converter
    convert the selected text to all lowercase, all uppercase, sentence case, or title case. supported via a dropdown in the toolbar in paragraphbuttons.
  2. summernote list styles
    customize the ul and ol list style. supported via a dropdown in the toolbar in listbuttons.
  3. summernote rtl
    switch the currently selected text between ltr and rtl format. supported via two buttons in the toolbar in paragraphbuttons.
  4. summernote at mention
    shows a dropdown of available mentions when the ‘@’ character is typed into the editor. the implementation requires that you pass a list of available mentions, and you can also provide a function to call when a mention is inserted into the editor.
  5. summernote file
    support picture files (jpg, png, gif, wvg, webp), audio files (mp3, ogg, oga), and video files (mp4, ogv, webm) in base64. supported via the image/audio/video/other file buttons in the toolbar in insertbuttons.

this list is not final, more can be added. if there’s a specific plugin you’d like to see support for, please file a feature request!

every plugin except summernote at mention is activated by default. they can be disabled by modifying the toolbar items, see above for details.

to activate summernote at mention:

htmleditorcontroller controller = htmleditorcontroller();
widget htmleditor = htmleditor(
  controller: controller, //required
  //other options
  plugins: [
    summernoteatmention(
      //returns the dropdown items on mobile
      getsuggestionsmobile: (string value) {
        list<string> mentions = ['test1', 'test2', 'test3'];
        return mentions
            .where((element) => element.contains(value))
            .tolist();
      },
      //returns the dropdown items on web
      mentionsweb: ['test1', 'test2', 'test3'],
      onselect: (string value) {
        print(value);
      }
    ),
  ]
);

htmleditoroptions parameters

this section contains longer descriptions for select parameters in htmleditoroptions. for parameters not mentioned here, see the parameters table above for a short description. if you have further questions, please file an issue.

autoadjustheight

default value: true

this option parameter sets the height of the editor automatically by getting the value returned by the js document.body.scrollheight and the toolbar globalkey (toolbarkey.currentcontext?.size?.height).

this is useful because the toolbar could have either 1 – 5 rows depending on the widget’s configuration, screen size, orientation, etc. there is no reliable way to tell how large the toolbar is going to be until after build() is executed, and thus simply hardcoding the height of the webview can induce either empty space at the bottom or a scrollable webview. by using the js and a globalkey on the toolbar widget, the editor can get the exact height and update the widget to reflect that.

there is a drawback: the webview will visibly shift size after the page is loaded. depending on how large the change is, it could be jarring. sometimes, it takes a second for the webview to adjust to the new size and you might see the editor page jump down/up a second or two after the webview container adjusts itself.

if this does not help your use case feel free to disable it, but the recommended value is true.

adjustheightforkeyboard

default value: true, only considered on mobile

this option parameter changes the height of the editor if the keyboard is active and it overlaps with the editor.

this is useful because webviews do not shift their view when the keyboard is active on flutter at the moment. this means that if your editor spans the height of the page, if the user types a long text they might not be able to see what they are typing because it is obscured by the keyboard.

when this parameter is enabled, the webview will shift to the perfect height to ensure all the typed content is visible, and as soon as the keyboard is hidden, the editor shifts back to its original height.

the webview does take a moment to shift itself back and forth after the keyboard pops up/keyboard disappears, but the delay isn’t too bad. it is highly recommended to have the webview in a scrollable and shouldensurevisible enabled if there are other widgets on the page – if the editor is on the bottom half of the page it will be scrolled to the top and then the height will be set accordingly, rather than the plugin trying to set the height for a webview obscured completely by the keyboard.

see below for an example use case.

if this does not help your use case feel free to disable it, but the recommended value is true.

filepath

this option parameter allows you to fully customize what html is loaded into the webview, by providing a file path to a custom html file from assets.

there is a particular format that is required/recommended when providing a file path for web, because the web implementation will load the html as a string and make changes to it directly using replaceall()., rather than using a method like evaluatejavascript() – because that does not exist on web.

on web, you should include the following:

  1. <!--darkcss--> inside <head> – this enables dark mode support
  2. <!--headstring--> inside <body> and below your summernote <div> – this allows the js and css files for any enabled plugins to be loaded
  3. <!--summernotescripts--> inside <body> and below your summernote <div> – required – this allows dart and js to communicate with each other. if you don’t include this, then methods/callbacks will do nothing.

notes:

  1. do not initialize the summernote editor in your custom html file! the package will take care of that.
  2. make sure to set the id for summernote to summernote-2! – <div id="summernote-2"></div>.
  3. make sure to include jquery and the summernote js/css in your file! the package does not do this for you.

    you can use these files from the package to avoid adding more asset files:

<script src="assets/packages/html_editor_enhanced/assets/jquery.min.js"></script>
<link href="assets/packages/html_editor_enhanced/assets/summernote-lite.min.css" rel="stylesheet">
<script src="assets/packages/html_editor_enhanced/assets/summernote-lite.min.js"></script>

see the example html file below for an actual example.

shouldensurevisible

default value: false

this option parameter will scroll the editor container into view whenever the webview is focused or text is typed into the editor.

you can only use this parameter if your htmleditor is inside a scrollview, otherwise it does nothing.

this is useful in cases where the page is a singlechildscrollview or something similar with multiple widgets (eg a form). when the user is going through the different fields, it will pop the webview into view, just like a textfield would scroll into in view if text is being typed inside it.

see below for an example with a good way to use this.

htmltoolbaroptions parameters

this section contains longer descriptions for select parameters in htmltoolbaroptions. for parameters not mentioned here, see the parameters table above for a short description. if you have further questions, please file an issue.

customtoolbarbuttons and customtoolbarbuttonsinsertionindices

these two parameters allow you to insert custom buttons and set where they are inserted into the toolbar widget list.

this would look something like this:

htmleditorcontroller controller = htmleditorcontroller();
widget htmleditor = htmleditor(
  controller: controller, //required
  //other options
  toolbaroptions: htmltoolbaroptions(
    defaulttoolbarbuttons: [
      stylebuttons(),
      fontsettingbuttons(),
      fontbuttons(),
      colorbuttons(),
      listbuttons(),
      paragraphbuttons(),
      insertbuttons(),
      otherbuttons(),
    ],
    customtoolbarbuttons: [
      //your widgets here
      button1(),
      button2(),
    ],
    customtoolbarinsertionindices: [2, 5]
  )
);

in the above example, we have defined two buttons to be inserted at indices 2 and 5. these buttons will not be inserted before fontsettingbuttons and before listbuttons, respectively! each default button group may have a few different sub-groups:

button group number of subgroups
stylebuttons 1
fontsettingbuttons 3
fontbuttons 2
colorbuttons 1
listbuttons 2
paragraphbuttons 5
insertbuttons 1
otherbuttons 2

if some of your buttons are deactivated, the number of subgroups could be reduced. the insertion index depends on these subgroups rather than the overall button group. an easy way to count the insertion index is to build the app and count the number of separator spaces between each button group/dropdown before the location you want to insert your button.

so with this in mind, button1 will be inserted between the first two subgroups in fontsettingbuttons, and button2 will be inserted between the two subgroups in fontbuttons.

when creating an onpressed/ontap/onchanged method for your widget, you can use controller.execcommand or any of the other methods on the controller to perform actions in the editor.

notes:

  1. using controller.editorcontroller.<method> will do nothing on web!
  2. if you don’t provide customtoolbarbuttonsinsertionindices, the plugin will insert your buttons at the end of the default toolbar list
  3. if you provide customtoolbarbuttonsinsertionindices, it must be the same length as your customtoolbarbuttons widget list.

linkinsertinterceptor, medialinkinsertinterceptor, otherfilelinkinsert, mediauploadinterceptor, and onotherfileupload

these callbacks help you intercept any links or files being inserted into the editor.

parameter type description
linkinsertinterceptor futureor<bool> function(string, string, bool) intercept any links inserted into the editor. the function passes the display text (string), the url (string), and whether it opens a new tab (bool).
medialinkinsertinterceptor futureor<bool> function(string, insertfiletype) intercept any media links inserted into the editor. the function passes the url (string).
mediauploadinterceptor futureor<bool> function(platformfile, insertfiletype) intercept any media files inserted into the editor. the function passes platformfile which holds all relevant file data. you can use this to upload into your server, to extract base64 data, perform file validation, etc. it also passes the file type (image/audio/video).
onotherfilelinkinsert function(string) intercept file link inserts other than image/audio/video. this handler is required when using the other file button, as the package has no built-in handlers. the function passes the url (string). it also passes the file type (image/audio/video)
onotherfileupload function(platformfile) intercept file uploads other than image/audio/video. this handler is required when using the other file button, as the package has no built-in handlers. the function passes platformfile which holds all relevant file data. you can use this to upload into your server, to extract base64 data, perform file validation, etc.

for linkinsertinterceptor, medialinkinsertinterceptor, and mediauploadinterceptor, you must return a bool to tell the plugin what it should do. when you return false, it assumes that you have handled the user request and taken action. when you return true, the plugin will use the default handlers to handle the user request.

onotherfilelinkinsert and onotherfileupload are required when using the “other file” button. this button isn’t active by default, so if you make it active, you must provide these functions, otherwise nothing will happen when the user inserts a file other than image/audio/video.

see below for an example.

onbuttonpressed and ondropdownchanged

these callbacks help you intercept any button presses or dropdown changes.

parameter type description
onbuttonpressed futureor<bool> function(buttontype, bool?, void function()?) intercept any button presses. the function passes the enum for the pressed button, the current selected status of the button (if applicable) and a function to update the status (if applicable).
ondropdownchanged futureor<bool> function(dropdowntype, dynamic, void function(dynamic)?) intercept any dropdown changes. the function passes the enum for the changed dropdown, the changed value, and a function to update the changed value (if applicable).

you must return a bool to tell the plugin what it should do. when you return false, it assumes that you have handled the user request and taken action. when you return true, the plugin will use the default handlers to handle the user request.

some buttons and dropdowns, such as copy/paste and the case converter, don’t need to update their changed value, so functions to update the value after handling the user request will not be provided for those buttons.

see below for an example.

custom toolbar position using toolbarposition.custom

you can use toolbarposition: toolbarposition.custom and the toolbarwidget() widget to fully customize exactly where you want to place the toolbar. the possibilities are endless – you could place the toolbar in a sticky header using slivers, you could decide to show/hide the toolbar whenever you please, or you could make the toolbar into a floating, draggable widget!

toolbarwidget() requires the htmleditorcontroller you created for the editor itself, along with the htmltoolbaroptions you supplied to the html constructor. these can be simply copy-pasted, no changed necessary.

a basic example where the toolbar is placed in a different location than normal:

htmleditorcontroller controller = htmleditorcontroller();
widget column = column(
  mainaxisalignment: mainaxisalignment.center,
  children: <widget>[
    htmleditor(
      controller: controller,
      htmleditoroptions: htmleditoroptions(
        hint: 'your text here...',
        shouldensurevisible: true,
        //initialtext: "<p>text content initial, if any</p>",
      ),
      htmltoolbaroptions: htmltoolbaroptions(
        toolbarposition: toolbarposition.custom, //required to place toolbar anywhere!
        //other options
      ),
      otheroptions: otheroptions(height: 550),
    ),
    //other widgets here
    widget1(),
    widget2(),
    toolbarwidget(
      controller: controller,
      htmltoolbaroptions: htmltoolbaroptions(
        toolbarposition: toolbarposition.custom, //required to place toolbar anywhere!
        //other options
      ),
    )
  ]
);

htmleditorcontroller parameters

processinputhtml, processoutputhtml, and processnewlineasbr

default values: true, true, false, respectively

processinputhtml replaces any occurrences of " with \", ' with \', and r, rn, n, and nn with empty strings. this is necessary to prevent syntax exceptions when inserting html into the editor as quotes and other special characters will not be escaped. if you have already sanitized and escaped all relevant characters from your html input, it is recommended to set this parameter false. you may also want to set this parameter false on web, as in testing it seems these characters are handled correctly by default, but that may not be the case for your html.

processoutputhtml replaces the output html with "" if:

  1. it is empty
  2. it is <p></p>
  3. it is <p><br></p>
  4. it is <p><br/></p>

these may seem a little random, but they are the three possible default/initial html codes the summernote editor will have. if you’d like to still receive these outputs, set the parameter false.

processnewlineasbr will replace n and nn with <br/>. this is only recommended when inserting plaintext as the initial value. in typical html any new-lines are ignored, and therefore this parameter defaults to false.

examples

see the example app to see how the majority of methods & callbacks can be used. you can also play around with the parameters to see how they function.

this section will be updated later with more specialized and specific examples as this library grows and more features are implemented.

example for linkinsertinterceptor, medialinkinsertinterceptor, otherfilelinkinsert, mediauploadinterceptor, and onotherfileupload:

example code

note: this example uses the http package.

import 'package:file_picker/file_picker.dart';
import 'package:http/http.dart' as http;

  widget editor = htmleditor(
    controller: controller,
    toolbaroptions: toolbaroptions(
      medialinkinsertinterceptor: (string url, insertfiletype type) {
        if (url.contains(website_url)) {
          controller.insertnetworkimage(url);
        } else {
          controller.inserttext("this file is invalid!");
        }
        return false;
      },
      mediauploadinterceptor: (platformfile file, insertfiletype type) async {
        print(file.name); //filename
        print(file.size); //size in bytes
        print(file.extension); //mime type (e.g. image/jpg)
        //either upload to server:
        if (file.bytes != null && file.name != null) {
          final request = http.multipartrequest('post', uri.parse("your_server_url"));
          request.files.add(http.multipartfile.frombytes("file", file.bytes, filename: file.name)); //your server may require a different key than "file"
          final response = await request.send();
          //try to insert as network image, but if it fails, then try to insert as base64:
          if (response.statuscode == 200) {
            controller.insertnetworkimage(response.body["url"], filename: file.name!); //where "url" is the url of the uploaded image returned in the body json
          } else {
            if (type == insertfiletype.image) {
              string base64data = base64.encode(file.bytes!);
              string base64image =
              """<img src="data:image/${file.extension};base64,$base64data" data-filename="${file.name}"/>""";
              controller.inserthtml(base64image);
            } else if (type == insertfiletype.video) {
              string base64data = base64.encode(file.bytes!);
              string base64image =
              """<video src="data:video/${file.extension};base64,$base64data" data-filename="${file.name}"/>""";
              controller.inserthtml(base64image);
            } else if (type == insertfiletype.audio) {
              string base64data = base64.encode(file.bytes!);
              string base64image =
              """<audio src="data:audio/${file.extension};base64,$base64data" data-filename="${file.name}"/>""";
              controller.inserthtml(base64image);
            }
          }
        }
        //or insert as base64:
        if (file.bytes != null) {
          if (type == insertfiletype.image) {
            string base64data = base64.encode(file.bytes!);
            string base64image =
            """<img src="data:image/${file.extension};base64,$base64data" data-filename="${file.name}"/>""";
            controller.inserthtml(base64image);
          } else if (type == insertfiletype.video) {
            string base64data = base64.encode(file.bytes!);
            string base64image =
            """<video src="data:video/${file.extension};base64,$base64data" data-filename="${file.name}"/>""";
            controller.inserthtml(base64image);
          } else if (type == insertfiletype.audio) {
            string base64data = base64.encode(file.bytes!);
            string base64image =
            """<audio src="data:audio/${file.extension};base64,$base64data" data-filename="${file.name}"/>""";
            controller.inserthtml(base64image);
          }
        }
        return false;
      },
    ),
  );

linkinsertinterceptor, onotherfilelinkinsert, and onotherfileupload can be implemented in a very similar way, except those do not use the insertfiletype enum in their function.

onotherfilelinkinsert and onotherfileupload also do not require a bool to be returned.

example for onbuttonpressed and ondropdownchanged

example code

  widget editor = htmleditor(
    controller: controller,
    toolbaroptions: toolbaroptions(
      onbuttonpressed: (buttontype type, bool? status, function()? updatestatus) {
        print("button '${describeenum(type)}' pressed, the current selected status is $status");
        //run a callback and return false and update the status, otherwise
        return true;
      },
      ondropdownchanged: (dropdowntype type, dynamic changed, function(dynamic)? updateselecteditem) {
        print("dropdown '${describeenum(type)}' changed to $changed");
        //run a callback and return false and update the changed value, otherwise
        return true;
      },
    ),
  );

example for adjustheightforkeyboard:

example code

class _htmleditorexamplestate extends state`<htmleditorexample>` {
  final htmleditorcontroller controller = htmleditorcontroller();

  @override
  widget build(buildcontext context) {
    return gesturedetector(
      ontap: () {
        if (!kisweb) {
          // this is extremely important to the example, as it allows the user to tap any blank space outside the webview,
          // and the webview will lose focus and reset to the original height as expected. 
          controller.clearfocus();
        }
      },
      child: scaffold(
        appbar: appbar(
          title: text(widget.title),
          elevation: 0,
        ),
        body: singlechildscrollview(
          child: column(
            mainaxisalignment: mainaxisalignment.center,
            children: `<widget>`[
              //other widgets
              htmleditor(
                controller: controller,
                htmleditoroptions: htmleditoroptions(
                  shouldensurevisible: true,
                  //adjustheightforkeyboard is true by default
                  hint: "your text here...",
                  //initialtext: "<p>text content initial, if any</p>",
                ),
                otheroptions: otheroptions(
                  height: 550,c
                ),
              ),
              //other widgets
            ],
          ),
        ),
      ),
    );
  }
}

example for shouldensurevisible:

example code

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:html_editor_enhanced/html_editor.dart';

class _examplestate extends state`<example>` {
  final htmleditorcontroller controller = htmleditorcontroller();

  @override
  widget build(buildcontext context) {
    return gesturedetector(
      ontap: () {
        if (!kisweb) {
          //these lines of code hide the keyboard and clear focus from the webview when any empty
          //space is clicked. these are very important for the shouldensurevisible to work as intended.
          systemchannels.textinput.invokemethod('textinput.hide');
          controller.editorcontroller!.clearfocus();
        }
      },
      child: scaffold(
        appbar: appbar(
          title: text(widget.title),
          elevation: 0,
          actions: [
            iconbutton(
               icon: icon(icons.check),
               tooltip: "save",
               onpressed: () {
                  //save profile details
               }
            ),
          ]   
        ),
        body: singlechildscrollview(
          child: column(
            mainaxisalignment: mainaxisalignment.center,
            children: <widget>[
              padding(
                padding: edgeinsets.only(left: 18, right: 18),
                child: textfield(
                  controller: titlecontroller,
                  textinputaction: textinputaction.next,
                  focusnode: titlefocusnode,
                  decoration: inputdecoration(
                      hinttext: "name",
                      border: inputborder.none
                  ),
                ),
              ),
              sizedbox(height: 16),
              htmleditor(
                controller: controller,
                htmleditoroptions: htmleditoroptions(
                  shouldensurevisible: true,
                  hint: "description",
                ),
                otheroptions: otheroptions(
                  height: 450,
                ),
              ),
              sizedbox(height: 16),
              padding(
                padding: edgeinsets.only(left: 18, right: 18),
                child: textfield(
                  controller: biocontroller,
                  textinputaction: textinputaction.next,
                  focusnode: biofocusnode,
                  decoration: inputdecoration(
                    hinttext: "bio",
                    border: inputborder.none
                  ),
                ),
              ),
              image.network("path_to_profile_picture"),
              iconbutton(
                 icon: icon(icons.edit, size: 35),
                 tooltip: "edit profile picture",
                 onpressed: () async {
                    //open gallery and make api call to update profile picture   
                 }
              ),
              //etc... just a basic form.
            ],
          ),
        ),
      ),
    );
  }
}

example html for filepath:

example html

<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <meta name="description" content="flutter summernote html editor">
    <meta name="author" content="tneotia">
    <title>summernote text editor html</title>
    <script src="assets/packages/html_editor_enhanced/assets/jquery.min.js"></script>
    <link href="assets/packages/html_editor_enhanced/assets/summernote-lite.min.css" rel="stylesheet">
    <script src="assets/packages/html_editor_enhanced/assets/summernote-lite.min.js"></script>
    <!--darkcss-->
</head>
<body>
<div id="summernote-2"></div>

<style>
  body {
      display: block;
      margin: 0px;
  }
  .note-editor.note-airframe, .note-editor.note-frame {
      border: 0px solid #a9a9a9;
  }
  .note-frame {
      border-radius: 0px;
  }
</style>
</body>
</html>

Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD

Comments are closed.