如何在 Flutter 小部件中创建超链接? [英] How to create a hyperlink in Flutter widget?

查看:39
本文介绍了如何在 Flutter 小部件中创建超链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个超链接以显示在我的 Flutter 应用程序中.

I would like to create a hyperlink to display in my Flutter app.

超链接应该嵌入在 Text 或类似的文本视图中,例如:

The hyper link should be embedded in a Text or similar text views like:

最后买的一本书是

有什么提示可以这样做吗?

Any hint to do this?

推荐答案

只需将 InkWell 包裹在 Text 小部件周围,并为 onTap 属性提供 UrlLauncher(来自服务库).在下面使用之前,将 UrlLauncher 作为 Flutter 包安装.

Just wrap an InkWell around a Text widget and supply an UrlLauncher (from the service library) to the onTap attribute. Install UrlLauncher as a Flutter package before using it below.

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart';


void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text('UrlLauncher'),
        ),
        body: new Center(
          child: new InkWell(
              child: new Text('Open Browser'),
              onTap: () => launch('https://docs.flutter.io/flutter/services/UrlLauncher-class.html')
          ),
        ),
      ),
    );
  }
}

您可以为文本小部件提供样式,使其看起来像一个链接.

You can supply a style to the Text widget to make it look like a link.

稍微调查一下这个问题后,我找到了一个不同的解决方案来实现您要求的内嵌"超链接.您可以使用带有 TextSpans.

After looking into the issue a little I found a different solution to implement the 'in line' hyperlinks you asked for. You can use the RichText Widget with enclosed TextSpans.

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text('UrlLauchner'),
        ),
        body: new Center(
          child: new RichText(
            text: new TextSpan(
              children: [
                new TextSpan(
                  text: 'This is no Link, ',
                  style: new TextStyle(color: Colors.black),
                ),
                new TextSpan(
                  text: 'but this is',
                  style: new TextStyle(color: Colors.blue),
                  recognizer: new TapGestureRecognizer()
                    ..onTap = () { launch('https://docs.flutter.io/flutter/services/UrlLauncher-class.html');
                  },
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

通过这种方式,您实际上可以突出显示一个单词并从中制作超链接;)

This way you can actually highlight one word and make a hyperlink out of it ;)

这篇关于如何在 Flutter 小部件中创建超链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆