How to play phone default ring tone with Flutter

Title is pretty straight forward.

First, import the ringtone from pub. Also, check out how to set it up.

Create a new dart file and paste this code:

import 'package:flutter/material.dart';
import 'package:ringtone/ringtone.dart';
import 'package:vibrate/vibrate.dart';

class RingtoneExample extends StatefulWidget {
  @override
  _RingtoneExampleState createState() => _RingtoneExampleState();
}

class _RingtoneExampleState extends State<RingtoneExample> {
  bool _isPlaying = false;

  _playRingtone() async {
    if (_isPlaying) {
      Ringtone.stop();

      setState((){
        _isPlaying = !_isPlaying;
      });

    } else {
      Ringtone.play();

      setState((){
        _isPlaying = !_isPlaying;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Ringtone Example')),
      body: Center(
          child: RaisedButton(
        child: Text(_isPlaying ? "Stop Ringtone" : "Play Ringtone"),
        color: Colors.red,
        onPressed: _playRingtone,
      )),
    );
  }
}

In main.dart:

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Code Snippets',
      theme: new ThemeData(primarySwatch: Colors.red),
      home: new RingtoneExample(),
    );
  }
}

If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment