我有一个与url_launcher示例代码非常相似的小部件:
import 'package:flutter/material.dart';
import 'url_functions.dart';
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return SafeArea(
child: ListView(children: [
new Center(
child: new RaisedButton(
onPressed: urlfunc.launchURL,
child: new Text('Show Map'),
),
),
], padding: EdgeInsets.all(8.0)));
}
}
当urlfunc.launchURL与我的小部件在同一个文件中并且名为_launchURL时,代码可以正常工作。
这是url_funtions.dart的代码:
import 'package:url_launcher/url_launcher.dart';
// https://pub.dartlang.org/packages/url_launcher
class urlfunc {
launchURL() async {
const url = 'https://flutter.io';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
}
我希望launchURL在单独的文件中,以便其他小部件也可以使用它。但是,当我将代码移至url_functions.dart时,出现以下错误消息:
错误:无法使用静态访问实例成员“ launchURL” 访问。
如何使用单独文件中的launchURL?
答案 0 :(得分:3)
您可以在功能之前使用Word 静态:
class urlfunc {
static launchURL() async {
const url = 'https://flutter.io';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
}
OR
您可以启动Class urlfunc,然后调用该函数:
class MyWidget extends StatelessWidget {
urlfunc myFunc = urlfunc();
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(title: Text("MiniCon")),
body: SafeArea(
child: ListView(children: [
new Center(
child: new RaisedButton(
onPressed: myFunc.launchURL(),
child: new Text('Show Map'),
),
),
], padding: EdgeInsets.all(8.0))),
);
}
}
class urlfunc {
launchURL() async {
const url = 'https://flutter.io';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
}