Having a problem with SwipeLoaded and SwipeLoading Conditions - android

I am facing an issue with SwipeLoading and SwipeLoaded Condition in my program. It is just When I am run only swipeLoaded condition. It will show only else part of the condition and if I run SwipeLoading Condition it will return only return part of the SwipeLoading Condition. Here is my code below.
import 'package:buis_talk/blocs/swipe/swipe_bloc.dart';
import 'package:buis_talk/widgets/widgets.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:buis_talk/models/models.dart';
class HomeScreen extends StatelessWidget {
static const String routeName = '/home';
const HomeScreen({Key? key}) : super(key: key);
static Route route() {
return MaterialPageRoute(
settings: const RouteSettings(name: routeName),
builder: (context) => const HomeScreen(),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: const CustomAppBar(
title: 'Home',
),
body: BlocBuilder<SwipeBloc, SwipeState>(
builder: (context, state) {
if (state is SwipeLoading) {
const Text("swipeloading");
return const Center(
child: CircularProgressIndicator(),
);
}
else if (state is SwipeLoaded){
// ignore: unnecessary_type_check
// if (state is SwipeLoaded) {
const Text("SwipeLoaded");
var userCount = state.users.length;
state.users[0];
if(state.users.isNotEmpty){
state.users[0];
}
// var userCount = (state.users).length;
return Column(
children: [
InkWell(
onDoubleTap: () {
Navigator.pushNamed(context, '/users',
arguments: state.users[0]
);
},
child: Draggable<User>(
data: state.users[0],
child: UserCard(user: state.users[0]),
feedback: UserCard(user: state.users[0]),
childWhenDragging:
(userCount > 1) ?
UserCard(user: state.users[0])
: Container(),
onDragEnd: (drag) {
if (drag.velocity.pixelsPerSecond.dx < 0) {
context.read<SwipeBloc>()
.add(SwipeLeft(user: state.users[0]));
print('Swiped left');
} else {
context.read<SwipeBloc>()
.add(SwipeRight(user: state.users[0]));
print('Swiped right');
}
},
),
),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 8.0,
horizontal: 60,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
InkWell(
onTap: () {
context.read<SwipeBloc>()
.add(SwipeLeft(user: state.users[0]));
print('Swiped left');
},
child: ChoiceButton(
width: 60,
height: 60,
size: 25,
hasGradient: false,
color: Theme.of(context).colorScheme.secondary,
icon: Icons.clear_rounded,
),
),
InkWell(
onTap: () {
context.read<SwipeBloc>()
.add(SwipeRight(user: state.users[0]));
print('Swiped right');
},
child: const ChoiceButton(
width: 80,
height: 80,
size: 30,
hasGradient: true,
color: Colors.white,
icon: Icons.coffee,
),
),
ChoiceButton(
width: 60,
height: 60,
size: 25,
hasGradient: false,
color: Theme.of(context).primaryColor,
icon: Icons.watch_later,
),
],
),
),
],
);
}
else if (state is SwipeError) {
return Center(
child: Text('There are\'t any more users.',
style: Theme.of(context).textTheme.headline3),
);
}
else {
return const Text('Something went wrong.');
}
}
// }
),
);
}
}
Here is the code which I write for the condition that are SwipeLoading, SwipeLoaded and SwipeError.
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:buis_talk/blocs/auth/auth_bloc.dart';
import 'package:buis_talk/models/user_model.dart';
import 'package:buis_talk/repositories/database/database_repository.dart';
import 'package:equatable/equatable.dart';
part 'swipe_event.dart';
part 'swipe_state.dart';
class SwipeBloc extends Bloc<SwipeEvent, SwipeState> {
final AuthBloc _authBloc;
final DatabaseRepository _databaseRepository;
StreamSubscription? _authSubscription;
SwipeBloc(
{required AuthBloc authBloc,
required DatabaseRepository databaseRepository,
})
: _authBloc = authBloc,
_databaseRepository = databaseRepository,
super(SwipeLoading()) {
on<LoadUsers>(_onLoadUsers);
on<UpdateHome>(_onUpdateHome);
on<SwipeLeft>(_onSwipeLeft);
on<SwipeRight>(_onSwipeRight);
_authSubscription = _authBloc.stream.listen((state) {
if (state.status == AuthStatus.authenticated) {
add(LoadUsers(userId: state.user!.uid));
}
});
}
void _onLoadUsers(
LoadUsers event,
Emitter<SwipeState> emit,
) {
_databaseRepository.getUser(event.userId).listen((users) {
print('$users');
// add(UpdateHome(users: users));
}
);
}
void _onUpdateHome(
UpdateHome event,
Emitter<SwipeState> emit,
) {
if(event.users != null) {
emit(SwipeLoaded(users: event.users!));
}
else {
emit(SwipeError());
}
}
void _onSwipeLeft(
SwipeLeft event,
Emitter<SwipeState> emit,
) {
if (state is SwipeLoaded) {
final state = this.state as SwipeLoaded;
List<User> users = List.from(state.users)..remove(event.user);
if(users.isNotEmpty) {
emit(SwipeLoaded(users: users));
} else {
emit(SwipeError());
}
try {
emit(
SwipeLoaded(
users: List.from(state.users)..remove(event.user),
),
);
} catch (_) {}
}
}
void _onSwipeRight(
SwipeRight event,
Emitter<SwipeState> emit,
) {
if (state is SwipeLoaded) {
final state = this.state as SwipeLoaded;
List<User> users = List.from(state.users)..remove(event.user);
if(users.isNotEmpty) {
emit(SwipeLoaded(users: users));
}
else {
emit(SwipeError());
}
if (state is SwipeLoaded) {
final state = this.state as SwipeLoaded;
try {
emit(SwipeLoaded(users: List.from(state.users)..remove(event.user),
),
);
} catch (_) {}
}
}
#override
Future<void> close() async {
_authSubscription?.cancel();
super.close();
}
}
}
This is the output after SwipeLoaded Condition
This is the output after SwipeLoading Condition

Related

every time i play a song and then want to skip to next it rethrow an exception i don't know why

enter image description hereI am building a music player app, and when I try the song to skip to next and sometimes when i hit pause button it just throws the exception , shown in the picture,
I tried to solve this but i could not find the solution, thanks in advance
here is my nowplaying.dart
`
import 'package:flutter/material.dart';
import 'package:just_audio/just_audio.dart';
import 'package:just_audio_background/just_audio_background.dart';
import 'package:on_audio_query/on_audio_query.dart';
import 'package:provider/provider.dart';
import '../../../../provider/song_model_provider.dart';
class NowPlaying extends StatefulWidget {
final List<SongModel> songModelList;
final AudioPlayer audioPlayer;
const NowPlaying(
{Key? key, required this.songModelList, required this.audioPlayer})
: super(key: key);
#override
State<NowPlaying> createState() => _NowPlayingState();
}
class _NowPlayingState extends State<NowPlaying> {
Duration _duration = const Duration();
Duration _position = const Duration();
bool _isPlaying = false;
List<AudioSource> songList = [];
int currentIndex = 0;
void popBack() {
Navigator.pop(context);
}
void seekToSeconds(int seconds) {
Duration duration = Duration(seconds: seconds);
widget.audioPlayer.seek(duration);
}
#override
void initState() {
super.initState();
parseSong();
}
void parseSong() {
try {
for (var element in widget.songModelList) {
songList.add(
AudioSource.uri(
Uri.parse(element.uri!),
tag: MediaItem(
id: element.id.toString(),
album: element.album ?? "No Album",
title: element.displayNameWOExt,
artUri: Uri.parse(element.id.toString()),
),
),
);
}
widget.audioPlayer.setAudioSource(
ConcatenatingAudioSource(children: songList),
);
widget.audioPlayer.play();
_isPlaying = true;
widget.audioPlayer.durationStream.listen((duration) {
if (duration != null) {
setState(() {
_duration = duration;
});
}
});
widget.audioPlayer.positionStream.listen((position) {
setState(() {
_position = position;
});
});
listenToEvent();
listenToSongIndex();
} on Exception catch (_) {
popBack();
}
}
void listenToEvent() {
widget.audioPlayer.playerStateStream.listen((state) {
if (state.playing) {
setState(() {
_isPlaying = true;
});
} else {
setState(() {
_isPlaying = false;
});
}
if (state.processingState == ProcessingState.completed) {
setState(() {
_isPlaying = false;
});
}
});
}
void listenToSongIndex() {
widget.audioPlayer.currentIndexStream.listen(
(event) {
setState(
() {
if (event != null) {
currentIndex = event;
}
context
.read<SongModelProvider>()
.setId(widget.songModelList[currentIndex].id);
},
);
},
);
}
#override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
return SafeArea(
child: Scaffold(
body: Container(
height: height,
width: double.infinity,
padding: const EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
IconButton(
onPressed: () {
popBack();
},
icon: const Icon(Icons.arrow_back_ios),
),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Center(
child: ArtWorkWidget(),
),
const SizedBox(
height: 15.0,
),
Text(
widget.songModelList[currentIndex].displayNameWOExt,
textAlign: TextAlign.center,
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18.0,
overflow: TextOverflow.ellipsis),
maxLines: 1,
),
const SizedBox(
height: 15.0,
),
Slider(
min: 0.0,
value: _position.inSeconds.toDouble(),
max: _duration.inSeconds.toDouble() + 1.0,
onChanged: (value) {
setState(
() {
seekToSeconds(value.toInt());
value = value;
},
);
},
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
_position.toString().split(".")[0],
),
Text(
_duration.toString().split(".")[0],
)
],
),
const SizedBox(
height: 20.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
IconButton(
onPressed: () {
if (widget.audioPlayer.hasPrevious) {
widget.audioPlayer.seekToPrevious();
}
},
icon: const Icon(
Icons.skip_previous,
size: 24.0,
),
),
IconButton(
onPressed: () {
setState(() {
if (_isPlaying) {
widget.audioPlayer.pause();
} else {
if (_position >= _duration) {
seekToSeconds(0);
} else {
widget.audioPlayer.play();
}
}
_isPlaying = !_isPlaying;
});
},
icon: Icon(
_isPlaying ? Icons.pause : Icons.play_arrow,
size: 40.0,
),
color: Theme.of(context).primaryColor,
),
IconButton(
onPressed: () {
if (widget.audioPlayer.hasNext) {
widget.audioPlayer.seekToNext();
}
},
icon: const Icon(
Icons.skip_next,
size: 24.0,
),
),
],
)
],
),
),
],
),
),
),
);
}
}
class ArtWorkWidget extends StatelessWidget {
const ArtWorkWidget({
Key? key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return QueryArtworkWidget(
id: context.watch<SongModelProvider>().id,
type: ArtworkType.AUDIO,
artworkHeight: 200,
artworkWidth: 200,
artworkFit: BoxFit.cover,
nullArtworkWidget: const Icon(
Icons.music_note,
size: 200,
),
);
}
}
`

How to show images in questions of Quiz app using Flutter and Firebase?

I'm creating a quiz app using Flutter & Firebase. I've fetched questions & options which don't contain images using Firebase, but I'm not able to fetch questions that contain an image in them.
This is a screenshot of the question, which doesn't have an image, I've fetched in the app:
Question with image is like shown below in excel format:
All these data except images are fetched from JSON file imported in Realtime Database in Firebase.
Below is the code where questions are fetched from Realtime database in Firebase:
import 'package:http/http.dart' as http;
import './question_model.dart';
import 'dart:convert';
import '../test.dart';
class DBconnect {
final url = Uri.parse(
'https://rto1-798fc-default-rtdb.firebaseio.com/questions.json');
Future<List<Question>> fetchQuestions() async {
return http.get(url).then((response) {
var data = json.decode(response.body) as Map<String, dynamic>;
List<Question> newQuestions = [];
data.forEach((key, value) {
var newQuestion = Question(
id: key,
title: value['title'],
options: Map.castFrom(value['options']),
);
newQuestions.add(newQuestion);
newQuestions.shuffle();
});
return newQuestions;
});
}
}
Below is the question model:
class Question {
final String id;
final String title;
final Map<String, bool> options;
Question({
required this.id,
required this.title,
required this.options,
});
#override
String toString() {
return 'Question(id: $id, title: $title, options: $options)';
}
}
Below is the question widget:
import 'package:flutter/material.dart';
import '../constants.dart';
class QuestionWidget extends StatelessWidget {
const QuestionWidget(
{Key? key,
required this.question,
required this.indexAction,
required this.totalQuestions})
: super(key: key);
final String question;
final int indexAction;
final int totalQuestions;
#override
Widget build(BuildContext context) {
return Container(
alignment: Alignment.centerLeft,
child: Text(
'Question ${indexAction + 1}/20: $question',
style: const TextStyle(
fontSize: 24.0,
color: neutral,
),
),
);
}
}
And this is the main page:
import 'package:flutter/material.dart';
import '../constants.dart';
import '../models/question_model.dart';
import '../widgets/question_widget.dart';
import '../widgets/next_button.dart';
import '../widgets/option_card.dart';
import '../widgets/result_box.dart';
import '../models/db_connect.dart';
class TestScreen extends StatefulWidget {
const TestScreen({Key? key}) : super(key: key);
#override
State<TestScreen> createState() => _TestScreenState();
}
class _TestScreenState extends State<TestScreen> {
var db = DBconnect();
late Future _questions;
Future<List<Question>> getData() async {
return db.fetchQuestions();
}
#override
void initState() {
_questions = getData();
super.initState();
}
int index = 0;
int score = 0;
bool isPressed = false;
bool isAlreadySelected = false;
void nextQuestion(int questionLength) {
if (index == 19 || score == 12) {
showDialog(
context: context,
barrierDismissible: false,
builder: (ctx) => ResultBox(
result: score,
questionLength: questionLength,
));
} else {
if (isPressed) {
setState(() {
index++;
isPressed = false;
isAlreadySelected = false;
});
} else {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: const Text('Please select any option'),
behavior: SnackBarBehavior.floating,
margin: EdgeInsets.symmetric(vertical: 20.0),
));
}
}
}
void checkAnswerAndUpdate(bool value) {
if (isAlreadySelected) {
return;
} else {
if (value == true) {
score++;
setState(() {
isPressed = true;
isAlreadySelected = false;
});
} else if (value == false) {
setState(() {
isPressed = true;
isAlreadySelected = false;
});
}
}
}
void startOver() {
setState(() {
Text('You have already attempted the LL Test');
});
}
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: _questions as Future<List<Question>>,
builder: (ctx, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
return Center(
child: Text('${snapshot.error}'),
);
} else if (snapshot.hasData) {
var extractedData = snapshot.data as List<Question>;
return Scaffold(
backgroundColor: background,
appBar: AppBar(
title: const Text('LL Test'),
backgroundColor: background,
shadowColor: Colors.transparent,
actions: [
Padding(
padding: const EdgeInsets.all(18.0),
child: Text(
'Score: $score',
style: TextStyle(fontSize: 18.0),
),
)
],
),
body: Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(horizontal: 10.0),
child: Column(
children: [
QuestionWidget(
question: extractedData[index].title,
indexAction: index,
totalQuestions: extractedData.length,
),
const Divider(
color: neutral,
),
const SizedBox(height: 25.0),
for (int i = 0;
i < extractedData[index].options.length;
i++)
GestureDetector(
onTap: () => checkAnswerAndUpdate(
extractedData[index].options.values.toList()[i]),
child: OptionCard(
option: extractedData[index].options.keys.toList()[i],
color: isPressed
? extractedData[index]
.options
.values
.toList()[i] ==
true
? correct
: incorrect
: neutral,
),
),
],
),
),
floatingActionButton: GestureDetector(
onTap: () => nextQuestion(extractedData.length),
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 10.0),
child: NextButton(),
),
),
floatingActionButtonLocation:
FloatingActionButtonLocation.centerFloat,
);
}
} else {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircularProgressIndicator(),
SizedBox(height: 20.0),
Text(
'Please Wait While Questions Are Loading..',
style: TextStyle(
backgroundColor: Color.fromARGB(255, 4, 82, 6),
color: neutral),
),
],
),
);
}
return const Center(
child: Text('NoData'),
);
},
);
}
}

Having a problem with Swipe Loaded and Swipe Loading Conditions

I am facing an issue with SwipeLoading and SwipeLoaded Condition in my program. It is just When I am run only swipeLoaded condition. It will show only else part of the condition and if I run SwipeLoading Condition it will return only return part of the SwipeLoading Condition. Here is my code below.
import 'package:buis_talk/blocs/swipe/swipe_bloc.dart';
import 'package:buis_talk/widgets/widgets.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:buis_talk/models/models.dart';
class HomeScreen extends StatelessWidget {
static const String routeName = '/home';
const HomeScreen({Key? key}) : super(key: key);
static Route route() {
return MaterialPageRoute(
settings: const RouteSettings(name: routeName),
builder: (context) => const HomeScreen(),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: const CustomAppBar(
title: 'Home',
),
body: BlocBuilder<SwipeBloc, SwipeState>(
builder: (context, state) {
if (state is SwipeLoading) {
const Text("swipeloading");
return const Center(
child: CircularProgressIndicator(),
);
}
else if (state is SwipeLoaded){
// ignore: unnecessary_type_check
// if (state is SwipeLoaded) {
const Text("SwipeLoaded");
var userCount = state.users.length;
state.users[0];
if(state.users.isNotEmpty){
state.users[0];
}
// var userCount = (state.users).length;
return Column(
children: [
InkWell(
onDoubleTap: () {
Navigator.pushNamed(context, '/users',
arguments: state.users[0]
);
},
child: Draggable<User>(
data: state.users[0],
child: UserCard(user: state.users[0]),
feedback: UserCard(user: state.users[0]),
childWhenDragging:
(userCount > 1) ?
UserCard(user: state.users[0])
: Container(),
onDragEnd: (drag) {
if (drag.velocity.pixelsPerSecond.dx < 0) {
context.read<SwipeBloc>()
.add(SwipeLeft(user: state.users[0]));
print('Swiped left');
} else {
context.read<SwipeBloc>()
.add(SwipeRight(user: state.users[0]));
print('Swiped right');
}
},
),
),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 8.0,
horizontal: 60,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
InkWell(
onTap: () {
context.read<SwipeBloc>()
.add(SwipeLeft(user: state.users[0]));
print('Swiped left');
},
child: ChoiceButton(
width: 60,
height: 60,
size: 25,
hasGradient: false,
color: Theme.of(context).colorScheme.secondary,
icon: Icons.clear_rounded,
),
),
InkWell(
onTap: () {
context.read<SwipeBloc>()
.add(SwipeRight(user: state.users[0]));
print('Swiped right');
},
child: const ChoiceButton(
width: 80,
height: 80,
size: 30,
hasGradient: true,
color: Colors.white,
icon: Icons.coffee,
),
),
ChoiceButton(
width: 60,
height: 60,
size: 25,
hasGradient: false,
color: Theme.of(context).primaryColor,
icon: Icons.watch_later,
),
],
),
),
],
);
}
else if (state is SwipeError) {
return Center(
child: Text('There are\'t any more users.',
style: Theme.of(context).textTheme.headline3),
);
}
else {
return const Text('Something went wrong.');
}
}
// }
),
);
}
}
Here is the code which I write for the condition that are SwipeLoading, SwipeLoaded and SwipeError.
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:buis_talk/blocs/auth/auth_bloc.dart';
import 'package:buis_talk/models/user_model.dart';
import 'package:buis_talk/repositories/database/database_repository.dart';
import 'package:equatable/equatable.dart';
part 'swipe_event.dart';
part 'swipe_state.dart';
class SwipeBloc extends Bloc<SwipeEvent, SwipeState> {
final AuthBloc _authBloc;
final DatabaseRepository _databaseRepository;
StreamSubscription? _authSubscription;
SwipeBloc(
{required AuthBloc authBloc,
required DatabaseRepository databaseRepository,
})
: _authBloc = authBloc,
_databaseRepository = databaseRepository,
super(SwipeLoading()) {
on<LoadUsers>(_onLoadUsers);
on<UpdateHome>(_onUpdateHome);
on<SwipeLeft>(_onSwipeLeft);
on<SwipeRight>(_onSwipeRight);
_authSubscription = _authBloc.stream.listen((state) {
if (state.status == AuthStatus.authenticated) {
add(LoadUsers(userId: state.user!.uid));
}
});
}
void _onLoadUsers(
LoadUsers event,
Emitter<SwipeState> emit,
) {
_databaseRepository.getUser(event.userId).listen((users) {
print('$users');
// add(UpdateHome(users: users));
}
);
}
void _onUpdateHome(
UpdateHome event,
Emitter<SwipeState> emit,
) {
if(event.users != null) {
emit(SwipeLoaded(users: event.users!));
}
else {
emit(SwipeError());
}
}
void _onSwipeLeft(
SwipeLeft event,
Emitter<SwipeState> emit,
) {
if (state is SwipeLoaded) {
final state = this.state as SwipeLoaded;
List<User> users = List.from(state.users)..remove(event.user);
if(users.isNotEmpty) {
emit(SwipeLoaded(users: users));
} else {
emit(SwipeError());
}
try {
emit(
SwipeLoaded(
users: List.from(state.users)..remove(event.user),
),
);
} catch (_) {}
}
}
void _onSwipeRight(
SwipeRight event,
Emitter<SwipeState> emit,
) {
if (state is SwipeLoaded) {
final state = this.state as SwipeLoaded;
List<User> users = List.from(state.users)..remove(event.user);
if(users.isNotEmpty) {
emit(SwipeLoaded(users: users));
}
else {
emit(SwipeError());
}
if (state is SwipeLoaded) {
final state = this.state as SwipeLoaded;
try {
emit(SwipeLoaded(users: List.from(state.users)..remove(event.user),
),
);
} catch (_) {}
}
}
#override
Future<void> close() async {
_authSubscription?.cancel();
super.close();
}
}
}

Flutter Web Sockets Not Connecting to Laravel

Using this package https://pub.dev/packages/laravel_echo
Current Code
import 'package:example/modal.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:laravel_echo/laravel_echo.dart';
import 'package:flutter_pusher_client/flutter_pusher.dart';
class PusherPage extends StatefulWidget {
#override
State<StatefulWidget> createState() => _PusherPage();
}
class _PusherPage extends State<PusherPage> {
List<String> _logs = new List();
Echo echo;
bool isConnected = false;
String channelType = 'public';
String channelName = '';
String event;
FlutterPusher pusherClient;
void onConnectionStateChange(ConnectionStateChange event) {
if (event.currentState == 'CONNECTED') {
log('connected');
setState(() {
isConnected = true;
});
} else if (event.currentState == 'DISCONNECTED') {
log('disconnected');
setState(() {
isConnected = false;
});
}
}
FlutterPusher getPusherClient() {
PusherOptions options = PusherOptions(
host: 'http://192.168.0.164:8000/laravel-websockets',
port: 6001,
encrypted: false,
);
return FlutterPusher('Laravel', options, lazyConnect: true);
}
void connect() {
pusherClient.connect(onConnectionStateChange: this.onConnectionStateChange);
}
#override
void initState() {
super.initState();
pusherClient = getPusherClient();
echo = new Echo({
'broadcaster': 'pusher',
'client': pusherClient,
// 'auth': {
// 'headers': {
// 'Authorization':
// 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjFkNTcxYzcyMTcwZmFmNDRmM2JkYjdkZTE2NmVmNTMzZTMwYjYwNjI2MjA5NjJlNWFhMmNkNTkyOTgwMzNlZmVlMjMyNzI2YTczMTY2NGZiIn0.eyJhdWQiOiIxIiwianRpIjoiMWQ1NzFjNzIxNzBmYWY0NGYzYmRiN2RlMTY2ZWY1MzNlMzBiNjA2MjYyMDk2MmU1YWEyY2Q1OTI5ODAzM2VmZWUyMzI3MjZhNzMxNjY0ZmIiLCJpYXQiOjE1NTAyNTE4MzIsIm5iZiI6MTU1MDI1MTgzMiwiZXhwIjoxNTgxNzg3ODMyLCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.Yhmzofhp8q32gcFmzQDAmm48cwmxqrZAi4Mfsbzp6pyzjzWziEM8isDrNqyQZANXUJP40LGJroK9LkVddHyqWtPQqTNXPv-Azx3tVy_YOkI-BhJhttKaiN7DTPD9gYiuUpINUjrqTVuzxzDHzXNmTemOVqVBABo4f6m9ZoWkdyNKyirPZHagofs4Lp1YR0--AgItZVCPl3DYrLdMY78a687edQaYA1q3HKWPggtxayN35BPoeOm08uxmE_YzYXRTzi6OxGLNcQnrC61NvWqTCZ5Ze4fvUuVRtASqybV1Y4oxcgs2kZYg1rxm5idHUrGwQE4fLmaGgDclBR7Ax-NbiN-VN1gJpB2D7eVYxigCVsCVBnoA5DtjKewg0axckthTXyxcTWJBnbarbbnPuI9ZWrxaZWcp4kWwosw9_pr7Ee_5Q-Uxr_ksZg6qZ3gVrqR9ZY0zZoQl4qEsbUGfLXLGrKj_NjeESOcUsPY6fACIy_Okttxto_a3y9wQwPMDJY-jxdLdZ1TdusZUJG8d5KJxfOUprqsCzju-TVnLZxpA-f15mI9zIcjtA-2PFYnUuukIxBw-FXzBWssrMLyTXxHl9Sux3WH5mtXDW_wbwoJj6aaLHBw28jgokbdlKx3QRWdTvAsALJM6nmDN4BWu2pIn05i5wpcUnxHIvcdOgoh3hn0'
// }
// }
});
}
log(String event) {
var now = new DateTime.now();
String formatted =
"${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}:${now.second.toString().padLeft(2, '0')}";
setState(() {
_logs.insert(0, "$formatted $event");
});
}
void _listenToChannel(String type, String name, String event) {
dynamic channel;
if (type == 'public') {
channel = echo.channel(name);
} else if (type == 'private') {
channel = echo.private(name);
} else if (type == 'presence') {
channel = echo.join(name).here((users) {
print(users);
}).joining((user) {
print(user);
}).leaving((user) {
print(user);
});
}
channel.listen(event, (e) {
log('channel: $name, event: $event');
});
}
#override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
child: Column(
children: <Widget>[
Flexible(
child: Container(
padding: EdgeInsets.all(15),
color: Colors.grey[100],
child: ListView.builder(
reverse: true,
itemCount: _logs.length,
itemBuilder: (BuildContext context, index) {
return Padding(
padding: EdgeInsets.symmetric(vertical: 4),
child: Text(_logs[index]),
);
},
),
),
),
Container(
height: 70,
decoration: BoxDecoration(
border: Border(
top: BorderSide(color: Colors.grey[300]),
),
),
child: Center(
child: ListView(
scrollDirection: Axis.horizontal,
children: <Widget>[
CupertinoButton(
onPressed: () {
showCupertinoModalPopup<void>(
context: context,
builder: (BuildContext context) {
return ChannelModal(
listen: true,
type: channelType,
name: channelName,
onTypeChanged: (value) {
setState(() {
channelType = value;
});
},
onNameChanged: (value) {
setState(() {
channelName = value;
});
},
onEventChanged: (value) {
setState(() {
event = value;
});
},
onSubmit: () {
log('Listening to channel: $channelName');
_listenToChannel(channelType, channelName, event);
Navigator.of(context).pop();
},
);
},
);
},
child: Text('listen to channel'),
),
CupertinoButton(
onPressed: () {
showCupertinoModalPopup<void>(
context: context,
builder: (BuildContext context) {
return ChannelModal(
listen: false,
name: channelName,
onNameChanged: (value) {
setState(() {
channelName = value;
});
},
onSubmit: () {
log('Leaving channel: $channelName');
echo.leave(channelName);
Navigator.of(context).pop();
},
);
},
);
},
child: Text('leave channel'),
),
Visibility(
visible: !isConnected,
child: CupertinoButton(
onPressed: () {
log('connecting');
this.connect();
},
child: Text('connect'),
),
),
Visibility(
visible: isConnected,
child: CupertinoButton(
onPressed: () {
log('disconnecting');
echo.disconnect();
},
child: Text('disconnect'),
),
),
CupertinoButton(
onPressed: () {
dynamic id = echo.sockedId();
log('socket_id: $id');
},
child: Text('get socket-id'),
),
CupertinoButton(
onPressed: () {
setState(() {
_logs = [];
});
},
child: Text('clear log'),
),
],
),
),
)
],
),
);
}
}
All i've changed is the host and port number.
The link http://192.168.0.164:8000/laravel-websockets is valid and takes me to the Laravel WebSockets Dashboard both on the Phone Browser and PC Browser so the IP and everything is correct. I'm just unable to connect it using the app
Error
W/System.err( 6777): SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
W/System.err( 6777): SLF4J: Defaulting to no-operation (NOP) logger implementation
W/System.err( 6777): SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Any Help would be Appreciated.

flutter_downloader, how do I get the values of url and filename from firebase into this flow and add to the list of download tasks?

I want to pass the values like name and link in the below code's final variables dynamically i.e when onPressed is executed. Any help would be appreciated... I have separated the section using ----- below.
In the example below all files have their names and links hardcoded which is less efficient and I want to pass these values dynamically and only when a user clicks on the required button
import 'dart:isolate';
import 'dart:ui';
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:permission_handler/permission_handler.dart';
const debug = true;
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await FlutterDownloader.initialize(debug: debug);
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
final platform = Theme.of(context).platform;
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(
title: 'Downloader',
platform: platform,
),
);
}
}
class MyHomePage extends StatefulWidget with WidgetsBindingObserver {
final TargetPlatform platform;
MyHomePage({Key key, this.title, this.platform}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
---------------------------------------------------------------------------------------
final _documents = [
{
'name': 'Learning Android Studio',
'link':
'http://barbra-coco.dyndns.org/student/learning_android_studio.pdf'
},
{
'name': 'Android Programming Cookbook',
'link':
'http://enos.itcollege.ee/~jpoial/allalaadimised/reading/Android-Programming-Cookbook.pdf'
},
{
'name': 'iOS Programming Guide',
'link':
'http://darwinlogic.com/uploads/education/iOS_Programming_Guide.pdf'
},
{
'name': 'Objective-C Programming (Pre-Course Workbook',
'link':
'https://www.bignerdranch.com/documents/objective-c-prereading-assignment.pdf'
},
];
final _images = [
{
'name': 'Arches National Park',
'link':
'https://upload.wikimedia.org/wikipedia/commons/6/60/The_Organ_at_Arches_National_Park_Utah_Corrected.jpg'
},
{
'name': 'Canyonlands National Park',
'link':
'https://upload.wikimedia.org/wikipedia/commons/7/78/Canyonlands_National_Park%E2%80%A6Needles_area_%286294480744%29.jpg'
},
{
'name': 'Death Valley National Park',
'link':
'https://upload.wikimedia.org/wikipedia/commons/b/b2/Sand_Dunes_in_Death_Valley_National_Park.jpg'
},
{
'name': 'Gates of the Arctic National Park and Preserve',
'link':
'https://upload.wikimedia.org/wikipedia/commons/e/e4/GatesofArctic.jpg'
}
];
final _videos = [
{
'name': 'Big Buck Bunny',
'link':
'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4'
},
{
'name': 'Elephant Dream',
'link':
'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4'
}
];
-------------------------------------------------------------------------------------------
List<_TaskInfo> _tasks;
List<_ItemHolder> _items;
bool _isLoading;
bool _permissionReady;
String _localPath;
ReceivePort _port = ReceivePort();
#override
void initState() {
super.initState();
_bindBackgroundIsolate();
FlutterDownloader.registerCallback(downloadCallback);
_isLoading = true;
_permissionReady = false;
_prepare();
}
#override
void dispose() {
_unbindBackgroundIsolate();
super.dispose();
}
void _bindBackgroundIsolate() {
bool isSuccess = IsolateNameServer.registerPortWithName(
_port.sendPort, 'downloader_send_port');
if (!isSuccess) {
_unbindBackgroundIsolate();
_bindBackgroundIsolate();
return;
}
_port.listen((dynamic data) {
if (debug) {
print('UI Isolate Callback: $data');
}
String id = data[0];
DownloadTaskStatus status = data[1];
int progress = data[2];
final task = _tasks?.firstWhere((task) => task.taskId == id);
if (task != null) {
setState(() {
task.status = status;
task.progress = progress;
});
}
});
}
void _unbindBackgroundIsolate() {
IsolateNameServer.removePortNameMapping('downloader_send_port');
}
static void downloadCallback(
String id, DownloadTaskStatus status, int progress) {
if (debug) {
print(
'Background Isolate Callback: task ($id) is in status ($status) and process ($progress)');
}
final SendPort send =
IsolateNameServer.lookupPortByName('downloader_send_port');
send.send([id, status, progress]);
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: Builder(
builder: (context) => _isLoading
? new Center(
child: new CircularProgressIndicator(),
)
: _permissionReady
? _buildDownloadList()
: _buildNoPermissionWarning()),
);
}
Widget _buildDownloadList() => Container(
child: ListView(
padding: const EdgeInsets.symmetric(vertical: 16.0),
children: _items
.map((item) => item.task == null
? _buildListSection(item.name)
: DownloadItem(
data: item,
onItemClick: (task) {
_openDownloadedFile(task).then((success) {
if (!success) {
Scaffold.of(context).showSnackBar(SnackBar(
content: Text('Cannot open this file')));
}
});
},
onAtionClick: (task) {
if (task.status == DownloadTaskStatus.undefined) {
_requestDownload(task);
} else if (task.status == DownloadTaskStatus.running) {
_pauseDownload(task);
} else if (task.status == DownloadTaskStatus.paused) {
_resumeDownload(task);
} else if (task.status == DownloadTaskStatus.complete) {
_delete(task);
} else if (task.status == DownloadTaskStatus.failed) {
_retryDownload(task);
}
},
))
.toList(),
),
);
Widget _buildListSection(String title) => Container(
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
child: Text(
title,
style: TextStyle(
fontWeight: FontWeight.bold, color: Colors.blue, fontSize: 18.0),
),
);
Widget _buildNoPermissionWarning() => Container(
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24.0),
child: Text(
'Please grant accessing storage permission to continue -_-',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.blueGrey, fontSize: 18.0),
),
),
SizedBox(
height: 32.0,
),
FlatButton(
onPressed: () {
_checkPermission().then((hasGranted) {
setState(() {
_permissionReady = hasGranted;
});
});
},
child: Text(
'Retry',
style: TextStyle(
color: Colors.blue,
fontWeight: FontWeight.bold,
fontSize: 20.0),
))
],
),
),
);
void _requestDownload(_TaskInfo task) async {
task.taskId = await FlutterDownloader.enqueue(
url: task.link,
headers: {"auth": "test_for_sql_encoding"},
savedDir: _localPath,
showNotification: true,
openFileFromNotification: true);
}
void _cancelDownload(_TaskInfo task) async {
await FlutterDownloader.cancel(taskId: task.taskId);
}
void _pauseDownload(_TaskInfo task) async {
await FlutterDownloader.pause(taskId: task.taskId);
}
void _resumeDownload(_TaskInfo task) async {
String newTaskId = await FlutterDownloader.resume(taskId: task.taskId);
task.taskId = newTaskId;
}
void _retryDownload(_TaskInfo task) async {
String newTaskId = await FlutterDownloader.retry(taskId: task.taskId);
task.taskId = newTaskId;
}
Future<bool> _openDownloadedFile(_TaskInfo task) {
return FlutterDownloader.open(taskId: task.taskId);
}
void _delete(_TaskInfo task) async {
await FlutterDownloader.remove(
taskId: task.taskId, shouldDeleteContent: true);
await _prepare();
setState(() {});
}
Future<bool> _checkPermission() async {
if (widget.platform == TargetPlatform.android) {
final status = await Permission.storage.status;
if (status != PermissionStatus.granted) {
final result = await Permission.storage.request();
if (result == PermissionStatus.granted) {
return true;
}
} else {
return true;
}
} else {
return true;
}
return false;
}
Future<Null> _prepare() async {
final tasks = await FlutterDownloader.loadTasks();
int count = 0;
_tasks = [];
_items = [];
_tasks.addAll(_documents.map((document) =>
_TaskInfo(name: document['name'], link: document['link'])));
_items.add(_ItemHolder(name: 'Documents'));
for (int i = count; i < _tasks.length; i++) {
_items.add(_ItemHolder(name: _tasks[i].name, task: _tasks[i]));
count++;
}
_tasks.addAll(_images
.map((image) => _TaskInfo(name: image['name'], link: image['link'])));
_items.add(_ItemHolder(name: 'Images'));
for (int i = count; i < _tasks.length; i++) {
_items.add(_ItemHolder(name: _tasks[i].name, task: _tasks[i]));
count++;
}
_tasks.addAll(_videos
.map((video) => _TaskInfo(name: video['name'], link: video['link'])));
_items.add(_ItemHolder(name: 'Videos'));
for (int i = count; i < _tasks.length; i++) {
_items.add(_ItemHolder(name: _tasks[i].name, task: _tasks[i]));
count++;
}
tasks?.forEach((task) {
for (_TaskInfo info in _tasks) {
if (info.link == task.url) {
info.taskId = task.taskId;
info.status = task.status;
info.progress = task.progress;
}
}
});
_permissionReady = await _checkPermission();
_localPath = (await _findLocalPath()) + Platform.pathSeparator + 'Download';
final savedDir = Directory(_localPath);
bool hasExisted = await savedDir.exists();
if (!hasExisted) {
savedDir.create();
}
setState(() {
_isLoading = false;
});
}
Future<String> _findLocalPath() async {
final directory = widget.platform == TargetPlatform.android
? await getExternalStorageDirectory()
: await getApplicationDocumentsDirectory();
return directory.path;
}
}
class DownloadItem extends StatelessWidget {
final _ItemHolder data;
final Function(_TaskInfo) onItemClick;
final Function(_TaskInfo) onAtionClick;
DownloadItem({this.data, this.onItemClick, this.onAtionClick});
#override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.only(left: 16.0, right: 8.0),
child: InkWell(
onTap: data.task.status == DownloadTaskStatus.complete
? () {
onItemClick(data.task);
}
: null,
child: Stack(
children: <Widget>[
Container(
width: double.infinity,
height: 64.0,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded(
child: Text(
data.name,
maxLines: 1,
softWrap: true,
overflow: TextOverflow.ellipsis,
),
),
Padding(
padding: const EdgeInsets.only(left: 8.0),
child: _buildActionForTask(data.task),
),
],
),
),
data.task.status == DownloadTaskStatus.running ||
data.task.status == DownloadTaskStatus.paused
? Positioned(
left: 0.0,
right: 0.0,
bottom: 0.0,
child: LinearProgressIndicator(
value: data.task.progress / 100,
),
)
: Container()
].where((child) => child != null).toList(),
),
),
);
}
Widget _buildActionForTask(_TaskInfo task) {
if (task.status == DownloadTaskStatus.undefined) {
return RawMaterialButton(
onPressed: () {
onAtionClick(task);
},
child: Icon(Icons.file_download),
shape: CircleBorder(),
constraints: BoxConstraints(minHeight: 32.0, minWidth: 32.0),
);
} else if (task.status == DownloadTaskStatus.running) {
return RawMaterialButton(
onPressed: () {
onAtionClick(task);
},
child: Icon(
Icons.pause,
color: Colors.red,
),
shape: CircleBorder(),
constraints: BoxConstraints(minHeight: 32.0, minWidth: 32.0),
);
} else if (task.status == DownloadTaskStatus.paused) {
return RawMaterialButton(
onPressed: () {
onAtionClick(task);
},
child: Icon(
Icons.play_arrow,
color: Colors.green,
),
shape: CircleBorder(),
constraints: BoxConstraints(minHeight: 32.0, minWidth: 32.0),
);
} else if (task.status == DownloadTaskStatus.complete) {
return Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text(
'Ready',
style: TextStyle(color: Colors.green),
),
RawMaterialButton(
onPressed: () {
onAtionClick(task);
},
child: Icon(
Icons.delete_forever,
color: Colors.red,
),
shape: CircleBorder(),
constraints: BoxConstraints(minHeight: 32.0, minWidth: 32.0),
)
],
);
} else if (task.status == DownloadTaskStatus.canceled) {
return Text('Canceled', style: TextStyle(color: Colors.red));
} else if (task.status == DownloadTaskStatus.failed) {
return Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text('Failed', style: TextStyle(color: Colors.red)),
RawMaterialButton(
onPressed: () {
onAtionClick(task);
},
child: Icon(
Icons.refresh,
color: Colors.green,
),
shape: CircleBorder(),
constraints: BoxConstraints(minHeight: 32.0, minWidth: 32.0),
)
],
);
} else {
return null;
}
}
}
class _TaskInfo {
final String name;
final String link;
String taskId;
int progress = 0;
DownloadTaskStatus status = DownloadTaskStatus.undefined;
_TaskInfo({this.name, this.link});
}
class _ItemHolder {
final String name;
final _TaskInfo task;
_ItemHolder({this.name, this.task});
}

Categories

Resources