Closed redimongo closed 2 years ago
So the following is going to look like a mess (sorry in advance)
However I needed away to do a GridView that allowed the user to change station.
When the app launches the app starts playing as it is meant to however when I click on a stations logo it does not start playing said station.
If anyone can assist that would be great.
Full code: `import 'dart:async'; import 'dart:convert'; import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:http/http.dart' as http; import 'package:flutter/services.dart'; import 'package:flutter_radio_player/flutter_radio_player.dart'; import './screens/trackswidget.dart'; import 'about_widget.dart';
/ TO FETCH PHOTOS /
Photo photoFromJson(String str) => Photo.fromJson(json.decode(str));
String photoToJson(Photo data) => json.encode(data.toJson());
class Photo { Photo({ this.data, });
List data;
factory Photo.fromJson(Map<String, dynamic> json) => Photo( data: List.from(json["data"].map((x) => Datum.fromJson(x))), );
Map<String, dynamic> toJson() => { "data": List.from(data.map((x) => x.toJson())), }; }
class Datum { Datum({ this.id, this.name, this.imageurl, this.website, this.listenlive, });
String id; String name; String imageurl; String website; String listenlive;
factory Datum.fromJson(Map<String, dynamic> json) => Datum( id: json["_id"], name: json["name"], imageurl: json["imageurl"], website: json["website"], listenlive: json["listenlive"], );
Map<String, dynamic> toJson() => { "_id": id, "name": name, "imageurl": imageurl, "website": website, "listenlive": listenlive, }; }
/ TO FETCH PHOTOS / Future fetchPhotos(http.Client client) async { final response = //await client.get('https://jsonplaceholder.typicode.com/photos'); await client.get('https://api.drn1.com.au/station/allstations'); // Use the compute function to run parsePhotos in a separate isolate. return compute(parsePhotos, response.body); }
// A function that converts a response body into a List. Photo parsePhotos(String responseBody) { return photoFromJson(responseBody); }
class PhotosList extends StatelessWidget { final Photo photos; FlutterRadioPlayer _flutterRadioPlayer = new FlutterRadioPlayer();
PhotosList({Key key, this.photos}) : super(key: key);
@override Widget build(BuildContext context) { return GridView.builder( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 1, childAspectRatio: MediaQuery.of(context).size.width / (MediaQuery.of(context).size.height / 4), //childAspectRatio: 200, ), scrollDirection: Axis.horizontal, itemCount: photos.data.length, itemBuilder: (context, index) { return RaisedButton( padding: const EdgeInsets.all(0), textColor: Colors.white, color: Colors.red, onPressed: () async { await _flutterRadioPlayer.setUrl(photos.data[index].listenlive+'?uuid=0000-0000-0000-0000', "false"); },
child: CachedNetworkImage( imageUrl: photos.data[index].imageurl, placeholder: (context, url) => CircularProgressIndicator(), errorWidget: (context, url, error) => Icon(Icons.error), ), ); // return Image.network(photos.data[index].imageurl, width: 80.0, height: 80.0,); }, );
} }
/END FETCH PHOTOS/
/ RADIO STATIONS / Radata radataFromJson(String str) => Radata.fromJson(json.decode(str));
String radataToJson(Radata data) => json.encode(data.toJson());
class Radata { Radata({ this.data, });
factory Radata.fromJson(Map<String, dynamic> json) => Radata( data: List.from(json["data"].map((x) => Radio.fromJson(x))), );
class Radio { Radio({ this.id, this.name, this.imageurl, this.website, this.listenlive, });
factory Radio.fromJson(Map<String, dynamic> json) => Radio( id: json["_id"], name: json["name"], imageurl: json["imageurl"], website: json["website"], listenlive: json["listenlive"], );
Map<String, dynamic> toJson() => { "_id": id, "name": name, "imageurl": imageurl, "website": website, "listenlive": listenlive, }; } / END RADIO STATIONS/
class Home extends StatefulWidget { var playerState = FlutterRadioPlayer.flutter_radio_paused;
var volume = 0.8;
@override State createState() { return _HomeState(); } }
class _HomeState extends State { Future _future; Future getHttp() async { http.Response response = await http.get("https://api.drn1.com.au/station/allstations"); if (response.statusCode == 200) { return radataFromJson(response.body); } }
bool check = true; int _currentIndex = 0; FlutterRadioPlayer _flutterRadioPlayer = new FlutterRadioPlayer();
@override void initState() { _future = getHttp(); initRadioService(); super.initState(); }
Future initRadioService() async { try { await _flutterRadioPlayer.init( "DRN1", "Live", "http://stream.radiomedia.com.au:8003/stream", "true"); } on PlatformException { print("Exception occurred while trying to register the services."); } //await _flutterRadioPlayer.play(); }
Future changestation(e) async{ try { await _flutterRadioPlayer.setUrl(e, "true"); // await _flutterRadioPlayer.play(); } on PlatformException { print("Exception occurred while trying to register the services."); } }
final List _children = [TracksWidget(), AboutWidget()];
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.black, title: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text('DRN',style: TextStyle(color: Colors.white, fontSize: 40.0),), const Text('1', style: TextStyle(color: Colors.red, fontSize: 40.0),) ], ), ), //body: _children[_currentIndex], body: Column(children: [ FutureBuilder( future: fetchPhotos(http.Client()), builder: (context, snapshot) { if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData ? Expanded(child: PhotosList(photos: snapshot.data)) : Center(child: CircularProgressIndicator()); }, ), ]), /*Column( children: [ SizedBox( height:200, child:ListView( // This next line does the trick. scrollDirection: Axis.horizontal, children: <Widget>[ Container( width: 200.0, height: 200.0, color: Colors.red, child: new RaisedButton( padding: const EdgeInsets.all(0), textColor: Colors.white, color: Colors.red, onPressed: () async { await changestation('http://stream.radiomedia.com.au:8006/stream'); }, child: CachedNetworkImage( imageUrl: "http://via.placeholder.com/200x200", placeholder: (context, url) => CircularProgressIndicator(), errorWidget: (context, url, error) => Icon(Icons.error), ), ), ), GestureDetector( child: SizedBox( width: 200, height:200, child: CachedNetworkImage( imageUrl: "http://via.placeholder.com/200x200", placeholder: (context, url) => CircularProgressIndicator(), errorWidget: (context, url, error) => Icon(Icons.error), ), ), onTap:() async { await changestation('http://stream.radiomedia.com.au:8015/stream');} ), /*child: new RaisedButton( padding: const EdgeInsets.all(0), textColor: Colors.white, color: Colors.blue, onPressed: () async { await changestation('http://stream.radiomedia.com.au:8015/stream'); }, child: CachedNetworkImage( imageUrl: "http://via.placeholder.com/200x200", placeholder: (context, url) => CircularProgressIndicator(), errorWidget: (context, url, error) => Icon(Icons.error), ), ),
*/ Container( width: 200.0, height: 200.0, color: Colors.green, ), Container( width: 200.0, height: 200.0, color: Colors.yellow, ), Container( width: 200.0, height: 200.0, color: Colors.orange, ), ], ), ),
FutureBuilder<List<Photo>>( future: fetchPhotos(http.Client()), builder: (context, snapshot) { if (snapshot.hasError) print(snapshot.error); return snapshot.hasData ? Expanded(child: PhotosList(photos: snapshot.data)) : Center(child: CircularProgressIndicator()); }, ), Row( children: <Widget>[ Expanded( child: new RaisedButton( padding: const EdgeInsets.all(8.0), textColor: Colors.white, color: Colors.blue, onPressed: () async { await changestation('http://stream.radiomedia.com.au:8015/stream'); }, child: new Text("Change Station"), ), ), Expanded( child: Text('Craft beautiful UIs', textAlign: TextAlign.center), ), Expanded( child: FittedBox( fit: BoxFit.contain, // otherwise the logo will be tiny child: const FlutterLogo(), ), ), ], ), ]),*/
/ body: Center( child: Column( children: [ StreamBuilder( stream: _flutterRadioPlayer.isPlayingStream, initialData: widget.playerState, builder: (BuildContext context, AsyncSnapshot 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: [ 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)) ], ), ), */
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, floatingActionButton: Container( height: 80.0, width: 80.0, child: FittedBox( child:FloatingActionButton( onPressed: () => { setState((){ if(check) { check = false; _flutterRadioPlayer.play(); print("false"); } else { check = true; _flutterRadioPlayer.pause(); print("true"); } }), }, child: Icon(check ? Icons.play_arrow: Icons.pause), backgroundColor: Colors.black, mini: true, ), ), ), bottomNavigationBar: BottomAppBar( shape: CircularNotchedRectangle(), child: Container( decoration: new BoxDecoration(color: new Color(0xFFFF0000)), height: 75, child: Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ IconButton( iconSize: 30.0, padding: EdgeInsets.only(left: 28.0), icon: Icon(Icons.home), onPressed: () { setState(() { onTabTapped(0); }); }, ), /* IconButton( iconSize: 30.0, padding: EdgeInsets.only(right: 28.0), icon: Icon(Icons.search), onPressed: () { setState(() { onTabTapped(1); }); }, ), IconButton( iconSize: 30.0, padding: EdgeInsets.only(left: 28.0), icon: Icon(Icons.notifications), onPressed: () { setState(() { onTabTapped(2); }); }, ),*/ IconButton( iconSize: 30.0, padding: EdgeInsets.only(right: 28.0), icon: Icon(Icons.info_outline), onPressed: () { setState(() { onTabTapped(1); }); }, ) ], ), ), ),// new );
}
void onTabTapped(int index) { setState(() { _currentIndex = index; }); } }`
Has been updated to v2. Please check the master branch
So the following is going to look like a mess (sorry in advance)
However I needed away to do a GridView that allowed the user to change station.
When the app launches the app starts playing as it is meant to however when I click on a stations logo it does not start playing said station.
If anyone can assist that would be great.
Full code: `import 'dart:async'; import 'dart:convert'; import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:http/http.dart' as http; import 'package:flutter/services.dart'; import 'package:flutter_radio_player/flutter_radio_player.dart'; import './screens/trackswidget.dart'; import 'about_widget.dart';
/ TO FETCH PHOTOS /
Photo photoFromJson(String str) => Photo.fromJson(json.decode(str));
String photoToJson(Photo data) => json.encode(data.toJson());
class Photo { Photo({ this.data, });
List data;
factory Photo.fromJson(Map<String, dynamic> json) => Photo( data: List.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => { "data": List.from(data.map((x) => x.toJson())),
};
}
class Datum { Datum({ this.id, this.name, this.imageurl, this.website, this.listenlive, });
String id; String name; String imageurl; String website; String listenlive;
factory Datum.fromJson(Map<String, dynamic> json) => Datum( id: json["_id"], name: json["name"], imageurl: json["imageurl"], website: json["website"], listenlive: json["listenlive"], );
Map<String, dynamic> toJson() => { "_id": id, "name": name, "imageurl": imageurl, "website": website, "listenlive": listenlive, }; }
/ TO FETCH PHOTOS / Future fetchPhotos(http.Client client) async {
final response =
//await client.get('https://jsonplaceholder.typicode.com/photos');
await client.get('https://api.drn1.com.au/station/allstations');
// Use the compute function to run parsePhotos in a separate isolate.
return compute(parsePhotos, response.body);
}
// A function that converts a response body into a List.
Photo parsePhotos(String responseBody) {
return photoFromJson(responseBody);
}
class PhotosList extends StatelessWidget { final Photo photos; FlutterRadioPlayer _flutterRadioPlayer = new FlutterRadioPlayer();
PhotosList({Key key, this.photos}) : super(key: key);
@override Widget build(BuildContext context) { return GridView.builder( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 1, childAspectRatio: MediaQuery.of(context).size.width / (MediaQuery.of(context).size.height / 4), //childAspectRatio: 200, ), scrollDirection: Axis.horizontal, itemCount: photos.data.length, itemBuilder: (context, index) { return RaisedButton( padding: const EdgeInsets.all(0), textColor: Colors.white, color: Colors.red, onPressed: () async { await _flutterRadioPlayer.setUrl(photos.data[index].listenlive+'?uuid=0000-0000-0000-0000', "false"); },
} }
/END FETCH PHOTOS/
/END FETCH PHOTOS/
/ RADIO STATIONS / Radata radataFromJson(String str) => Radata.fromJson(json.decode(str));
String radataToJson(Radata data) => json.encode(data.toJson());
class Radata { Radata({ this.data, });
List data;
factory Radata.fromJson(Map<String, dynamic> json) => Radata( data: List.from(json["data"].map((x) => Radio.fromJson(x))),
);
Map<String, dynamic> toJson() => { "data": List.from(data.map((x) => x.toJson())),
};
}
class Radio { Radio({ this.id, this.name, this.imageurl, this.website, this.listenlive, });
String id; String name; String imageurl; String website; String listenlive;
factory Radio.fromJson(Map<String, dynamic> json) => Radio( id: json["_id"], name: json["name"], imageurl: json["imageurl"], website: json["website"], listenlive: json["listenlive"], );
Map<String, dynamic> toJson() => { "_id": id, "name": name, "imageurl": imageurl, "website": website, "listenlive": listenlive, }; } / END RADIO STATIONS/
class Home extends StatefulWidget { var playerState = FlutterRadioPlayer.flutter_radio_paused;
var volume = 0.8;
@override State createState() {
return _HomeState();
}
}
class _HomeState extends State {
Future _future;
Future getHttp() async {
http.Response response =
await http.get("https://api.drn1.com.au/station/allstations");
if (response.statusCode == 200) {
return radataFromJson(response.body);
}
}
bool check = true; int _currentIndex = 0; FlutterRadioPlayer _flutterRadioPlayer = new FlutterRadioPlayer();
@override void initState() { _future = getHttp(); initRadioService(); super.initState(); }
Future initRadioService() async {
try {
await _flutterRadioPlayer.init(
"DRN1", "Live", "http://stream.radiomedia.com.au:8003/stream", "true");
} on PlatformException {
print("Exception occurred while trying to register the services.");
}
//await _flutterRadioPlayer.play();
}
Future changestation(e) async{
try {
await _flutterRadioPlayer.setUrl(e, "true");
// await _flutterRadioPlayer.play();
} on PlatformException {
print("Exception occurred while trying to register the services.");
}
}
final List _children = [TracksWidget(),
AboutWidget()];
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.black, title: Row( mainAxisAlignment: MainAxisAlignment.center, children:[
const Text('DRN',style: TextStyle(color: Colors.white, fontSize: 40.0),),
const Text('1', style: TextStyle(color: Colors.red, fontSize: 40.0),)
],
),
),
//body: _children[_currentIndex],
body: Column(children: [
FutureBuilder(
future: fetchPhotos(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
*/ Container( width: 200.0, height: 200.0, color: Colors.green, ), Container( width: 200.0, height: 200.0, color: Colors.yellow, ), Container( width: 200.0, height: 200.0, color: Colors.orange, ), ], ), ),
/ body: Center( child: Column( children:[
StreamBuilder(
stream: _flutterRadioPlayer.isPlayingStream,
initialData: widget.playerState,
builder:
(BuildContext context, AsyncSnapshot 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: [
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))
],
),
),
*/
}
void onTabTapped(int index) { setState(() { _currentIndex = index; }); } }`