Flutter直接拨打电话插件direct_phone_call的使用

Flutter直接拨打电话插件direct_phone_call的使用

direct_phone_call 是一个简单的 Flutter 插件,可以让你在应用内直接拨打电话,而无需进入电话拨号器。该插件还处理了权限请求。

使用方法

首先,在 pubspec.yaml 文件中添加依赖:

dependencies:
  direct_phone_call: ^1.0.0

Android 配置

无需任何额外配置。

iOS 配置

目前还在开发中。

示例代码

以下是一个完整的示例代码,展示了如何使用 direct_phone_call 插件来实现拨打电话功能。

import 'dart:developer';

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:direct_phone_call/direct_phone_call.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final GlobalKey<FormState> _formKey = GlobalKey();
  final TextEditingController _phoneNoController = TextEditingController();
  final _directPhoneCallPlugin = DirectPhoneCall();

  [@override](/user/override)
  void initState() {
    super.initState();
  }

  [@override](/user/override)
  void dispose() {
    super.dispose();
    _phoneNoController.dispose();
  }

  // 平台消息是异步的,因此我们在异步方法中初始化。
  Future<void> _makeACall() async {
    FocusScope.of(context).unfocus();
    if (_formKey.currentState!.validate()) {
      bool isCalled = false;
      try {
        isCalled = await _directPhoneCallPlugin.callNumber(
            number: _phoneNoController.text);
      } catch (e) {
        log('Exception : $e');
      }
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('拨打电话'),
        ),
        body: Container(
          height: 200,
          decoration: BoxDecoration(
            color: Colors.blue.withAlpha(10),
            borderRadius: BorderRadius.circular(30),
          ),
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 16,),
          margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 16,),
          child: Form(
            key: _formKey,
            child: Column(
              children: [
                const SizedBox(height: 24,),
                TextFormField(
                  controller: _phoneNoController,
                  style: const TextStyle(
                    fontSize: 12,
                    fontWeight: FontWeight.w500,
                  ),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return '请输入电话号码';
                    }
                    if (value.isNotEmpty && value.length < 7) {
                      return '无效的号码';
                    }
                    return null;
                  },
                  keyboardType: TextInputType.phone,
                  textInputAction: TextInputAction.done,
                  decoration: InputDecoration(
                    fillColor: Colors.white,
                    hintText: '电话号码',
                    hintStyle: const TextStyle(
                      color: Colors.black26,
                      fontSize: 12,
                      fontWeight: FontWeight.w400,
                    ),
                    prefixIcon: Icon(Icons.local_phone_rounded, color: Colors.green.shade800, size: 18,),
                    contentPadding: EdgeInsets.zero,
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10),
                      borderSide: const BorderSide(color: Colors.black38,),
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10),
                      borderSide: const BorderSide(color: Colors.black38,),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10),
                      borderSide: const BorderSide(color: Colors.blueAccent, width: 1.5,),
                    ),
                    errorBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10),
                      borderSide: BorderSide(color: Colors.red.shade800,),
                    ),
                    focusedErrorBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10),
                      borderSide: BorderSide(color: Colors.red.shade800, width: 1.5,),
                    ),
                  ),
                  onFieldSubmitted: (val) => _makeACall(),
                ),
                const SizedBox(height: 12,),
                ElevatedButton(
                  onPressed: () => _makeACall(),
                  style: ButtonStyle(
                    backgroundColor: WidgetStatePropertyAll(Colors.green.shade900,),
                    minimumSize: const WidgetStatePropertyAll(Size(100, 35),),
                  ),
                  child: Container(
                    child: const Text('拨打',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 13,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

更多关于Flutter直接拨打电话插件direct_phone_call的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter直接拨打电话插件direct_phone_call的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,关于在Flutter中使用direct_phone_call插件来实现直接拨打电话的功能,以下是一个详细的代码示例。这个插件允许你的Flutter应用通过点击按钮来拨打电话。

首先,你需要在你的pubspec.yaml文件中添加direct_phone_call依赖:

dependencies:
  flutter:
    sdk: flutter
  direct_phone_call: ^0.1.0  # 请检查最新版本号

然后运行flutter pub get来安装依赖。

接下来,在你的Flutter项目中,你可以按照以下步骤使用direct_phone_call插件:

  1. 导入插件: 在你的Dart文件中导入direct_phone_call插件。
import 'package:direct_phone_call/direct_phone_call.dart';
import 'package:flutter/material.dart';
  1. 请求权限: 在Android上拨打电话需要CALL_PHONE权限。你可以在AndroidManifest.xml中添加这个权限:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yourapp">

    <uses-permission android:name="android.permission.CALL_PHONE"/>
    <!-- 其他权限和配置 -->

</manifest>

注意:在运行时,你还需要请求这个权限(从Android 6.0及以上版本开始)。以下是一个请求权限的简单示例:

import 'package:permission_handler/permission_handler.dart';

Future<void> requestCallPermission() async {
  var status = await Permission.phone.status;
  if (!status.isGranted) {
    var result = await Permission.phone.request();
    if (!result.isGranted) {
      // 权限被拒绝
      throw Exception('CALL_PHONE permission is required.');
    }
  }
}

你需要添加permission_handler依赖到你的pubspec.yaml中:

dependencies:
  permission_handler: ^x.x.x  # 请检查最新版本号
  1. 实现拨打电话功能
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Phone Call Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
    // 请求拨打电话权限
    requestCallPermission().then((_) {
      // 权限请求成功后,可以在这里执行其他操作
    }).catchError((error) {
      // 处理权限请求失败的情况
      print(error);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Direct Phone Call Example'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            try {
              await DirectPhoneCall.dial('1234567890'); // 替换为你想拨打的电话号码
            } catch (e) {
              print(e); // 处理可能的错误,比如权限被拒绝或号码格式不正确
            }
          },
          child: Text('Call Number'),
        ),
      ),
    );
  }
}

在这个示例中,当用户点击按钮时,应用会尝试拨打电话。如果应用没有拨打电话的权限,它将抛出异常,你可以在catch块中处理这个异常。

请确保在实际应用中处理用户隐私和权限请求的最佳实践,包括在UI中清晰地告知用户为什么需要这个权限,以及在权限被拒绝时提供适当的反馈。

回到顶部