我有一个与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?
发布于 2018-10-15 05:23:53
您可以在函数前面使用Word 静态:
class urlfunc {
  static launchURL() async {
    const url = 'https://flutter.io';
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }}
或
您可以启动类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';
    }
  }
}https://stackoverflow.com/questions/52805086
复制相似问题