[018] 플러터 (Flutter) Tip - simple_html_css 패키지 사용하여 HTML 코드 표현하기

2025. 3. 25. 14:01모바일어플개발/Flutter Tips

반응형

안녕하세요~ totally 개발자입니다.

 

앱을 개발하다보면 HTML 코드를 표시해야 하는 경우가 생기는 데, 그 경우 사용하기 좋은 패키지가 있습니다. 바로 simple_html_css입니다. 

 

자세한 사용법은 아래 문서를 참고하시기 바라며 예제를 통해 바로 실습해보도록 하겠습니다.

https://pub.dev/packages/simple_html_css

 

simple_html_css | Flutter package

This package allows you to use simple HTML and inline CSS styles to style your text in flutter. A fork of css_text package.

pub.dev

 

Step 1: 먼저 pubspec.yaml 파일에 simple_html_css 패키지를 등록합니다. 현재 시점을 기준으로 5.0.0 버전입니다.

 

 

Step 2: 아래와 같이 simple_html_css를 import 해줍니다.

 

 

Step 3: 메인 클래스 내에 아래처럼 예제 HTML 코드를 변수로 넣어줍니다. (공식 문서에서 가져온 예제 HTML입니다)

MainApp({super.key});

String htmlContent = """
<body>
<h1 style='color: white; font-size:50px; font-style:italic;
background-color: rgb(0,122,255); font-weight:100;)'> Hello word! </h1>
<h1 style=''>Convert your <span style='color:lightseagreen;'>
HTML</span> and <span style='color:dodgerblue'>CSS</span>
easily into RichText</h1>
<p>Lorem ipsum dolor sit, consectetur adipiscing elit. Pellentesque in leo
id dui bibendum fringilla in et arcu. In vehicula vel est sed mattis.</p>
<p>We all spell <span style='color:crimson;
text-decoration: underline wavy;'>recieve</span> wrong.<br />Some times we
delete <del>stuff</del></p>
<div style='font-size:17px'>We write things that are
<span style='font-size:1.5em;'>Big,</span> <b>bold</b>&nbsp; or
<span style='color:brown'>colorful</span></div>
<p style='font-family:times;'>Some different FONT with
<span style='background-color:lightcyan;'>this part highlighted</span></p>
<div style='line-height:2; font-size:17px;'><b style='color: rgb(0,122,255);
font-weight:500;'>Finally some line heights.</b> Lorem ipsum dolor sit amet,
consectetur adipiscing elit. Pellentesque in leo id dui bibendum fringilla
in et arcu. In vehicula vel est sed mattis. Duis varius, sem non mattis.</div>
</body>
""";

 

 

Step 4: 아래 Widget build 부분에 RichText 형태로 넣어주시면 됩니다. 

 

 

Step 5: 실행 후 모습입니다. 

 

 

Step 6: 만약 <a> 태그로 링크 인식을 하고 싶은 경우라면 아래처럼 linksCallback를 활용하시면 됩니다. 링크 부분을 클릭하면 해당 링크를 표시하도록 했습니다.

 

 

Step 7: 기본적인 텍스트 스타일을 지정하고 싶은 경우에는 아래와 같이 하실 수 있습니다.

 

 

Step 8: HTML 코드를 태그 별로 이를 재정의하는 방법도 있습니다. 예시는 아래와 같으며, 설명을 드리면 p 태그를 아래와 같이 폰트 크기 20, amber 색상, 굵기를 700으로 조정한 것이고, overrideStyle이 Map<String, TextStyle>? 형태이므로 여러 태그들을 재정의할 수 있습니다.

 

 

감사합니다.

반응형