flutter调用系统的打电话、发短信、发邮件功能

介绍

类似于安卓的通过设置intent-action;
点击按钮就能跳转到系统的拨号,发短信,发邮件等界面。
效果如下:
flutter调用系统的打电话、发短信、发邮件功能_第1张图片

引入类库

url_launcher: ^5.0.3
get_it: ^1.0.3+2

如下图所示:
在配置文件pubspec.yaml中引入两个类库:
flutter调用系统的打电话、发短信、发邮件功能_第2张图片

创建一个服务

TelAndSmsService.dart

import 'package:url_launcher/url_launcher.dart';

class TelAndSmsService {

  void call(String number) => launch("tel:$number");
  void sendSms(String number) => launch("sms:$number");
  void sendEmail(String email) => launch("mailto:$email");
}

创建一个注册服务的工具类

ServiceLocator.dart

import 'package:get_it/get_it.dart';
import './TelAndSmsService.dart';

GetIt locator = GetIt();
void setupLocator() {
  locator.registerSingleton(TelAndSmsService());
}

应用主入口调用

main.dart

import 'package:flutter/material.dart';
import './view_sample.dart';
import 'ServiceLocator.dart';
void main()  {
// 注册服务
setupLocator();
// 运行主界面
runApp(ViewSample());
}


调用打电话,发短信,发邮件

view_sample.dart

import 'package:flutter/material.dart';
import 'ServiceLocator.dart';
import 'TelAndSmsService.dart';

class   ViewSample extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      title: 'view add or remove',
      theme: ThemeData(
        primaryColor: Colors.green,
      ),
      home: ViewPage(),
    );
  }
}

class ViewPage extends StatefulWidget{
  @override
  ViewPageState createState() => ViewPageState();

}
class ViewPageState extends State{
  bool toggle = true;
  final TelAndSmsService _service = locator();
  final String number = "123456789";
  final String email = "[email protected]";
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text('view page'),
      ),
      body: Container(
        child: Column(
          children: [
            RaisedButton(
              child: Text("打电话"),
              onPressed: ()=> _service.call(number)
              ,
            ),
            RaisedButton(
              child: Text("发短信"),
              onPressed: ()=> _service.sendSms(number)
            ),
            RaisedButton(
              child: Text("发邮件"),
                onPressed: ()=> _service.sendEmail(email)
            ),
          ],
        ),
      ),
    );
  }
  


}

你可能感兴趣的:(flutter)