- Notifications
You must be signed in to change notification settings - Fork85
A Tricky Solution for Implementing Inline-Image-In-Text Feature in Flutter.
License
bytedance/RealRichText
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
A Tricky Solution for ImplementingInline-Image-In-Text Feature in Flutter.
According to the related Flutter Issues(#2022) , Inline-Image-In-Text is a long-time(2 years) missing feature since RichText(or the underlying Paragraph) does only support pure text. But we can solve this problem in a simple/tricky way:
- Regard the images as a particular blank TextSpan, convert image's width and height to textspan's letterSpacing and fontSize. the origin paragraph will do the layout operation and leave the desired image space for us.
- Override the paint function,calculate the right offset via the getOffsetForCaret() api to draw the image over the space.
For more details, please refer to the source code.
The only thing you have to do is converting your origin text to a TextSpan/ImageSpan List first.
import'package:flutter/gestures.dart';import'package:flutter/material.dart';import'package:real_rich_text/real_rich_text.dart';voidmain()=>runApp(MyApp());classMyAppextendsStatefulWidget {@override_MyAppStatecreateState()=>_MyAppState();}class_MyAppStateextendsState<MyApp> {@overrideWidgetbuild(BuildContext context) {returnMaterialApp( home:Scaffold( appBar:AppBar( title:constText('Plugin example app'), ), body:Center( child:RealRichText([TextSpan( text:"A Text Link", style:TextStyle(color:Colors.red, fontSize:14), recognizer:TapGestureRecognizer() ..onTap= () {debugPrint("Link Clicked."); }, ),ImageSpan(AssetImage("packages/real_rich_text/images/emoji_9.png"), imageWidth:24, imageHeight:24, ),ImageSpan(AssetImage("packages/real_rich_text/images/emoji_10.png"), imageWidth:24, imageHeight:24, margin:EdgeInsets.symmetric(horizontal:10)),TextSpan( text:"哈哈哈", style:TextStyle(color:Colors.yellow, fontSize:14), ),TextSpan( text:"@Somebody", style:TextStyle( color:Colors.black, fontSize:14, fontWeight:FontWeight.bold), recognizer:TapGestureRecognizer() ..onTap= () {debugPrint("Link Clicked"); }, ),TextSpan( text:" #RealRichText# ", style:TextStyle(color:Colors.blue, fontSize:14), recognizer:TapGestureRecognizer() ..onTap= () {debugPrint("Link Clicked"); }, ),TextSpan( text:"showing a bigger image", style:TextStyle(color:Colors.black, fontSize:14), ),ImageSpan(AssetImage("packages/real_rich_text/images/emoji_10.png"), imageWidth:24, imageHeight:24, margin:EdgeInsets.symmetric(horizontal:5)),TextSpan( text:"and seems working perfect……", style:TextStyle(color:Colors.black, fontSize:14), ), ]), ), ), ); }}
ImageSpan must set the width & height properties.
if your image's width or height is not specific, you can wrap two RealRichText in a StatefulWidget, one for showing placeholder image and the other for showing the actual image when it is ready.