0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

flutterでurlをブラウザで開かせる

Posted at

必要なパッケージをインストールする

flutter pub add url_launcher

以下のようにurlを開く機能を実装

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatelessWidget {
  // URLを開く関数
  void launchURL(Uri url) async {
    if (await canLaunchUrl(url)) {
      await launchUrl(url);
    } else {
      throw 'Could not launch $url';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('URL Launcher Example'),
      ),
      body: Center(
        child: GestureDetector(
          onTap: () {
            launchURL(Uri.parse("https://www.example.com"));
          },
          child: Text(
            "Tap here to open the browser",
            style: TextStyle(decoration: TextDecoration.underline, color: Colors.blue),
          ),
        ),
      ),
    );
  }
}

外部ブラウザで開く場合はlaunchUrlmodeパラメータを追加する

void launchURL(Uri url) async {
    if (await canLaunchUrl(url)) {
      await launchUrl(
        url,
        mode: LaunchMode.externalApplication, // ここで外部ブラウザを指定
      );
    } else {
      throw 'Could not launch $url';
    }
  }

文字列がurlかどうかを判定する方法

Uri.parse()を使って例外が発生するかどうかをチェックする

bool isValidUri(String uri) {
  try {
    var parsedUri = Uri.parse(uri);
    return parsedUri.hasScheme; // スキーマが存在するか確認
  } catch (e) {
    // URIが無効な場合、例外が発生
    return false;
  }
}

void main() {
  var urls = [
    "https://www.example.com",
    "www.example.com",
    "example",
    "https://",
    "ftp://example.com"
  ];

  for (var url in urls) {
    print('$url is a valid URI? ${isValidUri(url)}');
  }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?