flutter - 如何在应用打开后立即在 Flutter 上运行调用 URL 的方法?
问题描述
今天我有一个调用方法的按钮_launchURL
。但我想在应用程序打开后立即调用此方法,而无需按下按钮。
import 'package:flutter/material.dart';
import 'package:flutter_custom_tabs/flutter_custom_tabs.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Custom Tabs Example',
theme: ThemeData(
primarySwatch: Colors.blue,
brightness: Brightness.light,
),
darkTheme: ThemeData(
primarySwatch: Colors.blue,
brightness: Brightness.dark,
),
home: Builder(
builder: (_context) => Scaffold(
appBar: AppBar(
title: const Text('Flutter Custom Tabs Example'),
brightness: Brightness.dark,
),
body: Center(
child: TextButton(
onPressed: () => _launchURL(_context),
child: Text(
'Open Page',
style: TextStyle(fontSize: 17),
),
),
),
),
),
);
}
Future<void> _launchURL(BuildContext context) async {
final theme = Theme.of(context);
try {
await launch(
'https://www.google.com/',
customTabsOption: CustomTabsOption(
toolbarColor: theme.primaryColor,
enableDefaultShare: true,
enableUrlBarHiding: true,
showPageTitle: true,
animation: CustomTabsSystemAnimation.slideIn(),
extraCustomTabs: const <String>[
// ref. https://play.google.com/store/apps/details?id=org.mozilla.firefox
'org.mozilla.firefox',
// ref. https://play.google.com/store/apps/details?id=com.microsoft.emmx
'com.microsoft.emmx',
],
),
safariVCOption: SafariViewControllerOption(
preferredBarTintColor: theme.primaryColor,
preferredControlTintColor: Colors.white,
barCollapsingEnabled: true,
entersReaderIfAvailable: false,
dismissButtonStyle: SafariViewControllerDismissButtonStyle.close,
),
);
} catch (e) {
// An exception is thrown if browser app is not installed on Android device.
debugPrint(e.toString());
}
}
}
解决方案
Widget build(BuildContext context) {
_launchURL(context); // <= here
return MaterialApp(
title: 'Flutter Custom Tabs Example',
theme: ThemeData(
primarySwatch: Colors.blue,
brightness: Brightness.light,
),
.
.
.
.
或者您可以在 initstate 中添加它,但您的方法需要 aBuildContext
才能工作。
推荐阅读
- python - 模数如何处理也小于除数的负股息?
- spring - Maven + Cucumber4 + Spring Integration - 无法执行黄瓜跑步者案例
- java - 如何获得基于两次 android 的 1Hour 的时隙间隔
- java - 我的音频播放器应用程序中正在播放多首歌曲
- c# - 如何使用 Roslyn CSharpCompilation 避免内存泄漏
- python - 我正在使用 txt 文件进行多项选择测验,但不知道如何随机化选项并给出分数
- regex - 出现在已知字符串和第一个右括号之间的字符串的正则表达式
- neo4j - 如何使用 Neo4j Cypher APOC 并行处理
- browser-automation - @test 下的方法不起作用,直到与 url 一起放置
- reactjs - 反应useCallback的useEffect依赖总是触发渲染