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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

50% Discounts On Projects

Do you have a custom project with a clear requirements, we are currently giving a 50% discount on all projects.

We will work with you to ensure we deliver what you need.

If you have questions or want to chat with us, you can reach us on Skype (henry.tochi)

Languages and technologies we use - Java, Kotlin, Laravel, Vue, React, Flutter, Swift and more.