How to create a hyperlink in Flutter widget?

后端 未结 7 1118
一个人的身影
一个人的身影 2020-12-02 10:47

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

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

相关标签:
7条回答
  • 2020-12-02 11:44

    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('UrlLauchner'),
            ),
            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.

    Update

    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 ;)

    0 讨论(0)
提交回复
热议问题