【问题标题】:How to use flutter url_launcher function from separate file?如何从单独的文件中使用颤振 url_launcher 函数?
【发布时间】:2018-10-14 17:08:49
【问题描述】:

我有一个与 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_functions.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?

【问题讨论】:

  • 尝试将函数_launchURL重命名为LaunchURL。我觉得因为下划线 (_) 函数不能从它所在的文件的任何地方调用。我之前遇到过这个问题,删除 _ 解决了我的问题。
  • 是的,已经做出了改变

标签: flutter


【解决方案1】:

您可以在函数前使用 Word Static

class urlfunc {
  static launchURL() async {
    const url = 'https://flutter.io';
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }

}

您可以启动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';
    }
  }
}

【讨论】:

  • 或者你可以实例化这个类。
  • 是的,这也是一种选择。
  • 请随时将其添加到您的答案中:)
  • 完成...@Dennis
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-08
  • 2022-06-15
  • 1970-01-01
  • 1970-01-01
  • 2013-03-27
  • 2021-05-26
  • 2013-05-08
相关资源
最近更新 更多