Flutter background service in custome time fireing function - flutter

I should implement feature which should fires function in every 10 seconds in the the background and I had tried out work manager but it minimal time is 15 min but I want 10 seconds and I cant find any packages or good example for it ,

dependencies:
flutter_background_service: ^0.2.4
Example:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_background_service/flutter_background_service.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
initializeService();
runApp(MyApp());
}
Future<void> initializeService() async {
final service = FlutterBackgroundService();
await service.configure(
androidConfiguration: AndroidConfiguration(
// this will executed when app is in foreground or background in separated isolate
onStart: onStart,
// auto start service
autoStart: true,
isForegroundMode: true,
),
iosConfiguration: IosConfiguration(
// auto start service
autoStart: true,
// this will executed when app is in foreground in separated isolate
onForeground: onStart,
// you have to enable background fetch capability on xcode project
onBackground: onIosBackground,
),
);
}
// to ensure this executed
// run app from xcode, then from xcode menu, select Simulate Background Fetch
void onIosBackground() {
WidgetsFlutterBinding.ensureInitialized();
print('FLUTTER BACKGROUND FETCH');
}
void onStart() {
WidgetsFlutterBinding.ensureInitialized();
final service = FlutterBackgroundService();
service.onDataReceived.listen((event) {
if (event!["action"] == "setAsForeground") {
service.setForegroundMode(true);
return;
}
if (event["action"] == "setAsBackground") {
service.setForegroundMode(false);
}
if (event["action"] == "stopService") {
service.stopBackgroundService();
}
});
// bring to foreground
service.setForegroundMode(true);
Timer.periodic(Duration(seconds: 1), (timer) async {
if (!(await service.isServiceRunning())) timer.cancel();
service.setNotificationInfo(
title: "My App Service",
content: "Updated at ${DateTime.now()}",
);
service.sendData(
{"current_date": DateTime.now().toIso8601String()},
);
});
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String text = "Stop Service";
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Service App'),
),
body: Column(
children: [
StreamBuilder<Map<String, dynamic>?>(
stream: FlutterBackgroundService().onDataReceived,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
final data = snapshot.data!;
DateTime? date = DateTime.tryParse(data["current_date"]);
return Text(date.toString());
},
),
ElevatedButton(
child: Text("Foreground Mode"),
onPressed: () {
FlutterBackgroundService()
.sendData({"action": "setAsForeground"});
},
),
ElevatedButton(
child: Text("Background Mode"),
onPressed: () {
FlutterBackgroundService()
.sendData({"action": "setAsBackground"});
},
),
ElevatedButton(
child: Text(text),
onPressed: () async {
final service = FlutterBackgroundService();
var isRunning = await service.isServiceRunning();
if (isRunning) {
service.sendData(
{"action": "stopService"},
);
} else {
service.start();
}
if (!isRunning) {
text = 'Stop Service';
} else {
text = 'Start Service';
}
setState(() {});
},
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
FlutterBackgroundService().sendData({
"hello": "world",
});
},
child: Icon(Icons.play_arrow),
),
),
);
}
}

you can use background_fetch, it a good lib for this propose.

Related

flutter how to fix permission handler error

I dont know how to resolve this red error part.
I copied this from internet then i got this error.
please help me to solve this.
This is my full code.
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:android_intent/android_intent.dart';
import 'package:geolocator/geolocator.dart';
class AskForPermission extends StatefulWidget {
#override
_AskForPermissionState createState() => _AskForPermissionState();
}
class _AskForPermissionState extends State<AskForPermission> {
final PermissionHandler permissionHandler = PermissionHandler();
Map<PermissionGroup, PermissionStatus>? permissions;
void initState() {
super.initState();
requestLocationPermission();
_gpsService();
}
Future<bool> _requestPermission(PermissionGroup permission) async {
final PermissionHandler _permissionHandler = PermissionHandler();
var result = await _permissionHandler.requestPermissions([permission]);
if (result[permission] == PermissionStatus.granted) {
return true;
}
return false;
}
/*Checking if your App has been Given Permission*/
Future<bool> requestLocationPermission({Function? onPermissionDenied}) async {
var granted = await _requestPermission(PermissionGroup.location);
if (granted!=true) {
requestLocationPermission();
}
debugPrint('requestContactsPermission $granted');
return granted;
}
/*Show dialog if GPS not enabled and open settings location*/
Future _checkGps() async {
if (!(await Geolocator.isLocationServiceEnabled())) {
if (Theme.of(context).platform == TargetPlatform.android) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Can't get gurrent location"),
content:const Text('Please make sure you enable GPS and try again'),
actions: <Widget>[
FlatButton(child: Text('Ok'),
onPressed: () {
final AndroidIntent intent = AndroidIntent(
action: 'android.settings.LOCATION_SOURCE_SETTINGS');
intent.launch();
Navigator.of(context, rootNavigator: true).pop();
_gpsService();
})],
);
});
}
}
}
/*Check if gps service is enabled or not*/
Future _gpsService() async {
if (!(await Geolocator.isLocationServiceEnabled())) {
_checkGps();
return null;
} else
return true;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Ask for permisions'),
backgroundColor: Colors.red,
),
body: Center(
child: Column(
children: <Widget>[
Text("All Permission Granted"),
],
))
);
}
}
I got the same problem - the code that worked with permission_handler ^8.0.0+2 didn't work anymore after I upgraded to ^8.3.0 - the code wouldn't compile, the Permission and the other classes where not "found" anymore (I use VS Code)
I fixed it by cleaning the pub cache:
flutter pub cache clean
and afterwards just get again the dependencies:
flutter pub get
PS: for upgrading to 8.3.0, I set targetSdkVersion and compileSdkVersion to 31 into build.gradle file
Install permission handler package from here. Then in your .dart file add import and call permission asking function somewhere. E.g. function like this asks for storage permission.
import 'package:permission_handler/permission_handler.dart';
Future<void> getStoragePermission() async {
if (await Permission.manageExternalStorage.request().isGranted) {
setState(() {});
} else if (await Permission.storage.request().isPermanentlyDenied) {
await openAppSettings();
} else if (await Permission.storage.request().isDenied) {
setState(() {});
}
}
Please refer to below code
https://pub.dev/packages/permission_handler/install
permission_handler: ^5.0.1+1
import 'package:permission_handler/permission_handler.dart';
import 'package:google_fonts/google_fonts.dart';
class MyApp extends StatelessWidget {
MyApp({Key key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primaryColor: Color(0xfff00B074),
textTheme: const TextTheme(
bodyText1: TextStyle(
fontSize: 18.0,
fontFamily: 'Barlow-Medium',
color: Color(0xff464255)),
),
),
home: PermissionHandlerScreen(),
);
}
}
class PermissionHandlerScreen extends StatefulWidget {
#override
_PermissionHandlerScreenState createState() =>
_PermissionHandlerScreenState();
}
class _PermissionHandlerScreenState extends State<PermissionHandlerScreen> {
#override
void initState() {
super.initState();
permissionServiceCall();
}
permissionServiceCall() async {
await permissionServices().then(
(value) {
if (value != null) {
if (value[Permission.storage].isGranted &&
value[Permission.camera].isGranted &&
value[Permission.microphone].isGranted) {
/* ========= New Screen Added ============= */
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => SplashScreen()),
);
}
}
},
);
}
/*Permission services*/
Future<Map<Permission, PermissionStatus>> permissionServices() async {
// You can request multiple permissions at once.
Map<Permission, PermissionStatus> statuses = await [
Permission.storage,
Permission.camera,
Permission.microphone,
//add more permission to request here.
].request();
if (statuses[Permission.storage].isPermanentlyDenied) {
openAppSettings();
setState(() {});
} else {
if (statuses[Permission.storage].isDenied) {
permissionServiceCall();
}
}
if (statuses[Permission.microphone].isPermanentlyDenied) {
openAppSettings();
setState(() {});
} else {
if (statuses[Permission.microphone].isDenied) {
permissionServiceCall();
}
}
if (statuses[Permission.camera].isPermanentlyDenied) {
openAppSettings();
setState(() {});
} else {
if (statuses[Permission.camera].isDenied) {
permissionServiceCall();
}
}
/*{Permission.camera: PermissionStatus.granted, Permission.storage: PermissionStatus.granted}*/
return statuses;
}
#override
Widget build(BuildContext context) {
permissionServiceCall();
return WillPopScope(
onWillPop: () {
SystemNavigator.pop();
},
child: Scaffold(
body: Container(
child: Center(
child: InkWell(
onTap: () {
permissionServiceCall();
},
child: Text("Click here to enable Enable Permission Screen")),
),
),
),
);
}
}
class SplashScreen extends StatelessWidget {
const SplashScreen({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () {
SystemNavigator.pop();
},
child: Scaffold(
body: Center(
child: Text(
"Splash Screen",
),
),
),
);
}
}
Add permission_handler dependency in your pubspec.yaml file.
Try the flutter pub get command. If already done, then refer to this link about the permission handler package.

stop closing showDialogue itself after 15 seconds

I am trying to display an information dialog when starting an application. After closing, another window appears asking for permission. I call it all in the initState function. It works, but I noticed that this first info dialog also closes on its own when 15 seconds have elapsed. How do I fix this? So that while the dialog is not closed by the user, the application will not be loaded further?
class _MyAppState extends State<MyApp> {
final keyIsFirstLoaded = 'is_first_loaded';
#override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) async {
final context = MyApp.navKey.currentState.overlay.context;
await showDialogIfFirstLoaded(context);
await initPlatformState();
});
}
showDialogIfFirstLoaded(BuildContext context, prefs) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
bool isFirstLoaded = prefs.getBool(keyIsFirstLoaded);
if (isFirstLoaded == null) {
return showDialog(
context: context,
builder: (BuildContext context) {
// return object of type Dialog
return new AlertDialog(
// title: new Text("title"),
content: new Text("//"),
actions: <Widget>[
new FlatButton(
child: new Text(".."),
onPressed: () {
Navigator.of(context).pop();
prefs.setBool(keyIsFirstLoaded, false);
},
),
],
);
},
);
}
}
initPlatformState() async {
print('Initializing...');
await BackgroundLocator.initialize();
print('Initialization done');
final _isRunning = await BackgroundLocator.isRegisterLocationUpdate();
setState(() {
isRunning = _isRunning;
});
onStart();
print('Running ${isRunning.toString()}');
}
#override
Widget build(BuildContext context) {
return MaterialApp(
localizationsDelegates: [
// ... app-specific localization delegate[s] here
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
navigatorKey:MyApp.navKey,
navigatorObservers: [
FirebaseAnalyticsObserver(analytics: analytics),
],
debugShowCheckedModeBanner: false,
title: '',
theme: ThemeData(),
home: new SplashScreen(),}
class SplashScreen extends StatefulWidget {
#override
_SplashScreenState createState() => new _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> with SingleTickerProviderStateMixin {
Timer _timer;
bool _visible = true;
startTime() async {
_timer = Timer(new Duration(seconds: 5), navigationPage);
}
void navigationPage() {
Navigator.of(context).pushReplacementNamed('/home');
}
#override
void initState() {
_timer = Timer(Duration(seconds: 4),
() => setState(
() {
_visible = !_visible;
},
),
);
startTime();
super.initState();
}
#override
void dispose() {
_timer.cancel();
super.dispose();
}
#override
Widget build(BuildContext context) {
return new Stack(
children: <Widget>[
Container(
width: double.infinity,
child: Image.asset('images/bg.jpg',
fit: BoxFit.cover,
height: 1200,
),
),
Container(
width: double.infinity,
height: 1200,
color: Color.fromRGBO(0, 0, 0, 0.8),
),
Container(
alignment: Alignment.center,
child: Row(
children: <Widget>[
Expanded(
flex: 2,
child: Container(
child: Text(''),
),
),
],
),
),
],
);
}
}
This code displays an Alert dialogue if the user is new and after the button click, it will direct him to another dialogue.
I have tested the code and it doesn't close after 15 seconds. I'm still not sure what you're trying to accomplish but I hope this helps.
Init State
#override
void initState() {
WidgetsBinding.instance.addPostFrameCallback((_) async {
await dialog1(context);
//await initPlatformState();
});
super.initState();
}
Alert Dialog 1
dialog1(BuildContext context)async{
SharedPreferences prefs = await SharedPreferences.getInstance();
bool isFirstLoaded = prefs.getBool("keyIsFirstLoaded")??true;
if (isFirstLoaded) {
showDialog(
barrierDismissible: false, //disables user from dismissing the dialog by clicking out of the dialog
context: context, builder: (ctx) {
return AlertDialog(
title: Text("dialog 1"), content: Text("Content"), actions: [
TextButton(
child: new Text(".."),
onPressed: () async{
Navigator.pop(ctx);
await dialog2(context);
prefs.setBool("keyIsFirstLoaded", false);
},
),],);
},);
}else{
//not first time
}
}
Alert Dialog 2
void dialog2(BuildContext context)async{
print("dialog 2");
showDialog(context: context, builder: (context) {
return AlertDialog(title: Text("Dialog 2"),content: Text("permissions"),actions: [
TextButton(
child: new Text("close"),
onPressed: () async{
Navigator.pop(context);
//await dialog1(context); //uncomment if you want to go back to dialoge 1
},
),],);
},);
}
You can return a value from Navigator in the first dialog
Navigator.of(context).pop(true);
prefs.setBool(keyIsFirstLoaded, false);
Once it receive true, then only call the second method.
var value = await showDialogIfFirstLoaded(context);
if(value == true) {
await initPlatformState();
}

How to get state changed value after widget build?

I have simple application where I work with user location. On first app open I will ask from user to allow location and then save to var. But when I try check inside widget location allow status it is return old value instance of changed value.
Code
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:yandex_mapkit/yandex_mapkit.dart';
import 'package:permission_handler/permission_handler.dart';
class PlacesListScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return _Map();
}
}
class _Map extends StatefulWidget {
#override
_MapState createState() => _MapState();
}
class _MapState extends State<_Map> {
YandexMapController controller;
PermissionStatus _permissionStatus = PermissionStatus.undetermined;
#override
void initState() {
super.initState();
_requestPermission();
}
Future<void> _requestPermission() async {
Map<Permission, PermissionStatus> permissions =
await [Permission.location].request();
setState(() {
_permissionStatus = permissions[Permission.location];
});
}
void _showMessage(BuildContext context, Text text) {
final ScaffoldState scaffold = Scaffold.of(context);
scaffold.showSnackBar(
SnackBar(
content: text,
action: SnackBarAction(
label: 'OK', onPressed: scaffold.hideCurrentSnackBar),
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('App Name'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.add),
onPressed: null,
),
],
),
body: Text('App Content'),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
FloatingActionButton(
onPressed: () async {
if (_permissionStatus == PermissionStatus.granted) {
await Future.wait([
controller.moveToUser(),
controller.showUserLayer(
iconName: 'lib/assets/arrow.png',
arrowName: 'lib/assets/user_location1.png',
accuracyCircleFillColor: Colors.green.withOpacity(0.5),
)
]);
} else {
_showMessage(context, const Text('Permission Denied'));
}
},
child: Icon(Icons.place, color: Colors.white),
backgroundColor: Colors.green,
heroTag: 'showUserLocation',
),
],
),
);
}
}
Using FloatingActionButton I tried check Permission status in my code. But my var _permissionStatus doesn't updated when user allowed location. How to fix this problem and get changed value from state?
You can use this package: https://pub.dev/packages/location
and then you can read the permission status:
Location location = new Location();
PermissionStatus _permissionGranted;
_permissionGranted = await location.hasPermission();
if (_permissionGranted == PermissionStatus.denied) {
_permissionGranted = await location.requestPermission();
if (_permissionGranted != PermissionStatus.granted) {
return;
}
}
another way:
location.hasPermision().then(PermissionStatus status){
if (_permissionGranted == PermissionStatus.denied){
location.requestPermission().then((PermissionStatus requestStatus){
// save the value
}
);
}
});
You need to know when user grand the permission then you know it, you must use the wrap your widget with FocusScope like this:
first define this:
final _focusNode = FocusScopeNode();
then wrap it with this:
return FocusScope(
node: _focusNode,
child: WillPopScope(
onWillPop: () async {
_requestPermission();
},.....

Hive Flutter Usage

I am a newbee at Flutter and Hive, just learning. Here are some questions:
I am using Value Listenable Builder, when I press the "Person age Up" person1 age is not updated, but if I press the setstate then is updated.
How to auto update?
Hive is a database; if I press the "Add person", it adds, and I see when I press "Print person lenght" but when reloaded the app person length is changed to 1 again, all adds removed:
import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'departmentClass.dart';
import 'person.dart';
void main() async {
await Hive.initFlutter('test');
Hive.registerAdapter(DepartmentAdapter());
Hive.registerAdapter(PersonAdapter());
await Hive.openBox<Department>('testBox');
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final Box testBox = Hive.box<Department>('testBox');
#override
Widget build(BuildContext context) {
if (testBox.isEmpty) {
final List<Person> personsAll = [];
final person1 = new Person(23, "Maria");
personsAll.add(person1);
var mydepartment = new Department(34, "newD", personsAll);
Hive.box<Department>('testBox').put("01", mydepartment);
}
return ValueListenableBuilder(
valueListenable: testBox.listenable(),
builder: (context, box, widget) {
return MaterialApp(
home: SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text("Hive Test"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Hive Sample"),
RaisedButton(
child: Text("Clear Box"),
onPressed: () {
Hive.box<Department>('testBox').clear();
},
),
Text("Person1 Age Now: " + box.get("01").persons[0].age.toString()),
RaisedButton(
child: Text("Person age UP"),
onPressed: () {
box.get("01").persons[0].age++;
print(box.get("01").persons[0].age);
},
),
RaisedButton(
child: Text("Set State"),
onPressed: () {
setState(() {});
},
),
RaisedButton(
child: Text("Add person "),
onPressed: () {
final person2 = new Person(23, "Maria");
box.get("01").persons.add(person2);
},
),
RaisedButton(
child: Text("Print person lenght "),
onPressed: () {
print("Persons: " + Hive.box<Department>('testBox').get("01").persons.length.toString());
},
)
],
)),
),
),
);
},
);
}
}
First of all when you open a box it is better to declare it's type in generic;
final Box<Department> testBox = Hive.box<Department>('testBox');
Secondly if you want to notify the box that you're listening via ValueListenableBuilder, you need to put the value inside the box every time you changed the value;
box.get("01").persons[0].age++;
// this will notify the valuelistenablebuilder
box.put("01", box.get("01"));
print(box.get("01").persons[0].age);
I have written an app where I used both Hive and cubits and it worked really well.
Below is AppDatabase class, where I have only one box ('book') and I open it up in the initialize() method, like below:
The whole application and tutorial is here.
const String _bookBox = 'book';
#Singleton()
class AppDatabase {
AppDatabase._constructor();
static final AppDatabase _instance = AppDatabase._constructor();
factory AppDatabase() => _instance;
late Box<BookDb> _booksBox;
Future<void> initialize() async {
await Hive.initFlutter();
Hive.registerAdapter<BookDb>(BookDbAdapter());
_booksBox = await Hive.openBox<BookDb>(_bookBox);
}
Future<void> saveBook(Book book) async {
await _booksBox.put(
book.id,
BookDb(
book.id,
book.title,
book.author,
book.publicationDate,
book.about,
book.readAlready,
));
}
Future<void> deleteBook(int id) async {
await _booksBox.delete(id);
}
Future<void> deleteAllBooks() async {
await _booksBox.clear();
}
}

Creating a share class Flutter

I am not sure if this is possible, but with SwiftUI I have a mediaplayer class which has all my media player controls in it.
I am wondering if it is possible to have a flutter class file that hold flutter_radio_player and 1 media player that can change audio source?
The issue I have ran into with our old android app is we can't change the track without it creating a whole new media player.
I can't find any sample code on how to do this.
My code currently:
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter_radio_player/flutter_radio_player.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
var playerState = FlutterRadioPlayer.flutter_radio_paused;
var volume = 0.8;
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
int _currentIndex = 0;
final List<Widget> _children = [
new MyApp(),
];
FlutterRadioPlayer _flutterRadioPlayer = new FlutterRadioPlayer();
#override
void initState() {
super.initState();
initRadioService();
}
Future<void> initRadioService() async {
try {
await _flutterRadioPlayer.init(
"DRN1", "Live", "http://stream.radiomedia.com.au:8003/stream", "false");
} on PlatformException {
print("Exception occurred while trying to register the services.");
}
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Flutter Radio Player Example'),
),
body: Center(
child: Column(
children: <Widget>[
StreamBuilder(
stream: _flutterRadioPlayer.isPlayingStream,
initialData: widget.playerState,
builder:
(BuildContext context, AsyncSnapshot<String> snapshot) {
String returnData = snapshot.data;
print("object data: " + returnData);
switch (returnData) {
case FlutterRadioPlayer.flutter_radio_stopped:
return RaisedButton(
child: Text("Start listening now"),
onPressed: () async {
await initRadioService();
});
break;
case FlutterRadioPlayer.flutter_radio_loading:
return Text("Loading stream...");
case FlutterRadioPlayer.flutter_radio_error:
return RaisedButton(
child: Text("Retry ?"),
onPressed: () async {
await initRadioService();
});
break;
default:
return Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
IconButton(
onPressed: () async {
print("button press data: " +
snapshot.data.toString());
await _flutterRadioPlayer.playOrPause();
},
icon: snapshot.data ==
FlutterRadioPlayer
.flutter_radio_playing
? Icon(Icons.pause)
: Icon(Icons.play_arrow)),
IconButton(
onPressed: () async {
await _flutterRadioPlayer.stop();
},
icon: Icon(Icons.stop))
]);
break;
}
}),
Slider(
value: widget.volume,
min: 0,
max: 1.0,
onChanged: (value) => setState(() {
widget.volume = value;
_flutterRadioPlayer.setVolume(widget.volume);
})),
Text("Volume: " + (widget.volume * 100).toStringAsFixed(0))
],
),
),
),
);
}
}
FlutterRadioPlayer Author here. With the new release of the player, you can do this.
You just have to call
_flutterRadioPlayer.setUrl('URL_HERE')
The player will automatically set the old stream to a halt and start the new stream. Yes, you can set it to autoplay when ready as well. Just refer to the docs in new release.