개발 - Flutter

[ 001 ] Flutter (플러터) - 텍스트 내 링크 연동

벌꿀오소리 엘 2024. 10. 7. 15:07

이번 포스팅에서는

String Text 내부에

링크가 있는 경우

해당 부분만 링크화에 대해서

포스팅 하려고 한다.

 


 

 

일반적으로

Text가 "외부 링크" 라는

확신이 있으면,

단순히

아래 처럼 처리 하면 된다.

 

 

1) 일반 URL 외부링크 처리

 

 

import 'package:url_launcher/url_launcher.dart';

                      launchUrl(Uri.parse(
                          'https:${controller.cultureData.value.event_url}'));

 

 

 

2) Text 내부 링크 처리

 

이 경우

Text 중에서,

link만 파악해서

url 처리를 해줘야 하는데,

딱 위에 맞는 라이브러리가 있다.

flutter_linkify

https://pub.dev/packages/flutter_linkify

 

flutter_linkify | Flutter package

Turns text URLs and emails into clickable inline links in text for Flutter.

pub.dev

 

 

 

라이브러리를 설치 했다면

사용 자체는 매우 간단하다.

 

 

 

Linkify(
                                onOpen: (link) async {
                                  if (!await launchUrl(Uri.parse(link.url))) {
                                    throw Exception(
                                        'Could not launch ${link.url}');
                                  }
                                },
                                text: data.text
                                style: TextStyle(
                                  height: 0.9.w,
                                  color: defaultBlack,
                                  fontSize: 12.sp,
                                ),
                                linkStyle: TextStyle(
                                  height: 0.9.w,
                                  color: blue,
                                  decoration: TextDecoration.underline,
                                  decorationColor: blue,
                                  fontSize: 12.sp,
                                ),
                              ),

 

 

  • Linkify 라는 위젯안에
    • onOpen - url 눌렀을 때 작동 방식 - 현재는 url 잘못됐을 때, 에러 던지도록 함.
    • text - 전체 text 를 의미, 이중에서 url 인지해서 링크 걸어줌.
    • style -기본적인 text Style
    • linkStyle - 링크가 걸리는 text Style

 

위처럼 매우 간단하다.

 

 

 

문제가 생긴다면,

댓글로 알려주면, 최대한 상세히 답변 드리겠습니다.

도움이 되었다면

댓글과 좋아요 부탁드립니다.