Related
users.dart
class UsersPage extends StatefulWidget {
const UsersPage(
BuildContext context, {
Key? key,
//required String title,
}) : super(key: key);
final String title = "Flutter DataTable";
#override
UsersPageState createState() => UsersPageState();
}
class UsersPageState extends State<UsersPage> {
var appBarHeight = AppBar().preferredSize.height;
PageController page = PageController();
//Create the (Global) Keys
final GlobalKey<FormState> _formKey = GlobalKey();
final GlobalKey<ScaffoldState> _drawerscaffoldkey =
GlobalKey<ScaffoldState>();
// late GlobalKey<ScaffoldState> _scaffoldKey;
final ScrollController horizontal = ScrollController(),
vertical = ScrollController();
// bool _isSortAsc = true;
int _currentSortColumn = 0;
bool _isAscending = true;
late bool _isUpdating;
late Users _selectedUser;
late String _titleProgress;
late List<Users> _users;
late TextEditingController _firstNameController;
late TextEditingController _lastNameController;
var list;
var index;
#override
void initState() {
super.initState();
_users = [];
_isUpdating = false;
_titleProgress = widget.title;
// _scaffoldKey = GlobalKey();
_firstNameController = TextEditingController();
_lastNameController = TextEditingController();
_getUsers();
}
static List<Users> parseResponse(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Users>((json) => Users.fromJson(json)).toList();
}
_setValues(Users user) {
_firstNameController.text = user.firstName;
_lastNameController.text = user.lastName;
setState(() {
_isUpdating = true;
});
}
_showProgress(String message) {
setState(() {
_titleProgress = message;
});
}
_getUsers() {
_showProgress('Loading User...');
Services.getUsers().then((users) {
setState(() {
// _users = users.cast<User>();
_users = users;
});
_showProgress(widget.title);
debugPrint("Length: ${users.length}");
});
}
_deleteUser(Users user) {
_showProgress('Deleting User...');
Services.deleteUser(user.userId).then((result) {
if ('success' == result) {
setState(() {
_users.remove(user);
});
_getUsers();
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
//============================== Appbar code here... ==============================
appBar: AppBar(
title: const Text("Users Page"),
leading: IconButton(
onPressed: () {
//on drawer menu pressed
if (_drawerscaffoldkey.currentState!.isDrawerOpen) {
//if drawer is open, then close the drawer
Navigator.pop(context);
} else {
_drawerscaffoldkey.currentState?.openDrawer();
//if drawer is closed then open the drawer.
}
},
icon: const Icon(Icons.menu),
),
actions: <Widget>[]),
//
body: Scaffold(
//second scaffold
key: _drawerscaffoldkey, //set gobal key defined above
//======================================== Drawer code here... ==========================
drawer: Row(children: [
SideMenu(
controller: page,
style: SideMenuStyle(
//showTooltip: false,
displayMode: SideMenuDisplayMode.auto,
hoverColor: Colors.blue[100],
selectedColor: Colors.blue,
selectedTitleTextStyle: const TextStyle(color: Colors.white),
selectedIconColor: Colors.white,
decoration: const BoxDecoration(
//borderRadius: BorderRadius.all(Radius.circular(10)),
color: Colors.black12,
border: Border(
right: BorderSide(
color: Colors.black,
width: 1.0,
),
),
boxShadow: [
BoxShadow(
color: Colors.white,
offset: Offset(0.0, 0.0),
blurRadius: 0.0,
spreadRadius: 0.0,
),
],
//backgroundBlendMode: BlendMode.color
), /*backgroundColor: Colors.black12*/
),
title: Column(
children: [
const SizedBox(
height: 10,
),
ConstrainedBox(
constraints: const BoxConstraints(
maxHeight: 150,
maxWidth: 150,
),
child: Image.asset(
'lib/assets/images/crm_logo.png',
),
),
const Divider(
indent: 8.0,
endIndent: 8.0,
),
],
),
items: [
SideMenuItem(
priority: 0,
title: 'Dashboard',
icon: const Icon(Icons.home),
onTap: () {
Navigator.pushReplacementNamed(context, '/AdminPage');
//sideMenu.changePage(const AdminPage(title: 'Dashboard'));
},
tooltipContent: "Dashboard",
),
SideMenuItem(
priority: 1,
title: 'Sales Team',
icon: const Icon(Icons.assignment_ind),
//GestureDetector(
onTap: () {
//const UsersPage(title: 'title');
Navigator.pushReplacementNamed(context, '/UsersPage');
},
//),
),
],
),
]),
//====================================== Main Body Code Here... =============================
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.only(
left: 320.0, top: 35.0, right: 35.0, bottom: 100.0),
child: Column(
children: <Widget>[
const Align(
alignment: Alignment.topLeft,
child: Text("Users View Page",
style: TextStyle(
fontSize: 24,
)),
),
Padding(
padding: const EdgeInsets.only(left: 400.0),
child: Row(
//mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
OutlinedButton(
style: TextButton.styleFrom(
foregroundColor: Colors.blueGrey,
side: const BorderSide(
color: Colors.black26,
width: 0.5,
),
padding: const EdgeInsets.symmetric(
vertical: 16.0, horizontal: 20.0),
),
onPressed: () {
//_submit();
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => const AddUserPage(
title: '',
)));
},
child: const Text("Add User",
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
)),
),
const SizedBox(
width: 100.0,
),
/* OutlinedButton(
style: TextButton.styleFrom(
foregroundColor: Colors.blueGrey,
side: const BorderSide(
color: Colors.black26,
width: 0.5,
),
padding: const EdgeInsets.symmetric(
vertical: 16.0, horizontal: 20.0),
),
onPressed: () {
debugPrint('Edit Button Clicked');
},
child: const Text("Update User",
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
)),
),
const SizedBox(
width: 100.0,
), */
OutlinedButton(
style: TextButton.styleFrom(
foregroundColor: Colors.blueGrey,
side: const BorderSide(
color: Colors.black26,
width: 0.5,
),
padding: const EdgeInsets.symmetric(
vertical: 16.0, horizontal: 20.0),
),
onPressed: () {
//_submit();
_getUsers();
/* Navigator.of(context).push(MaterialPageRoute(
builder: (context) => UsersPage(context))); */
},
child: const Text("Refresh",
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
)),
),
],
),
),
const SizedBox(
height: 30,
),
Scrollbar(
thickness: 5,
controller: horizontal,
trackVisibility: true,
child: SingleChildScrollView(
controller: horizontal,
scrollDirection: Axis.horizontal,
child: DataTable(
/* sortColumnIndex: _currentSortColumn,
sortAscending: _isSortAsc,
sortColumnIndex : 0,
sortAscending : 10.0, */
sortColumnIndex: _currentSortColumn,
sortAscending: _isAscending,
showCheckboxColumn: true,
// sortColumnIndex: 0,
// sortAscending: true,
/* selected: true,
showEditIcon: true, */
border: TableBorder.all(
width: 1.0,
color: Colors.black45,
),
headingRowColor: MaterialStateProperty.resolveWith(
(states) => Colors.blueGrey),
headingTextStyle: TextStyle(
fontWeight: FontWeight.bold, color: Colors.white),
columns: const [
/* DataColumn(
label: Text(
"LINE NO. #",
),
numeric: false,
tooltip: "This is the Line No."), */
DataColumn(
label: Text("USER ID"),
numeric: false,
tooltip: "This is the user id",
/* onSort: (int columnIndex, bool ascending) {
setState(() {
_currentSortColumn = columnIndex;
if (_isAscending == true) {
_isAscending = false;
// sort the users list in Ascending, order by ID
_users.sort((userA, userB) =>
userB.userId.compareTo(userA.userId));
} else {
_isAscending = true;
// sort the users list in Descending, order by ID
_users.sort((userA, userB) =>
userA.userId.compareTo(userB.userId));
}
});
} */
),
DataColumn(
label: Text(
"FIRST NAME",
),
numeric: false,
tooltip: "This is the last name"),
DataColumn(
label: Text("LAST NAME"),
numeric: false,
tooltip: "This is the last name"),
DataColumn(
label: Text("ACTIONS"),
numeric: false,
tooltip: "Related Actions"),
],
rows: _users
.map(
(user) => DataRow(
cells: [
DataCell(
Text(user.userId),
/* onTap: () {
debugPrint("Tapped ${user.userId}");
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
AddUpdateUserPage()));
_setValues(user);
_selectedUser = user;
}, */
),
DataCell(
Text(
user.firstName,
),
onTap: () {
debugPrint("Tapped ${user.firstName}");
_setValues(user);
_selectedUser = user;
},
),
DataCell(
Text(
user.lastName /* .toUpperCase() */,
),
onTap: () {
debugPrint("Tapped ${user.lastName}");
_setValues(user);
_selectedUser = user;
},
),
DataCell(
Row(
children: [
IconButton(
icon: Icon(Icons.edit),
tooltip: "Edit",
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
AddUpdateUserPage(
list: list,
index: index),
),
);
debugPrint("Edit Mode Enabled...");
},
),
IconButton(
icon: Icon(Icons.delete),
tooltip: "Delete",
onPressed: () {
_deleteUser(user);
debugPrint("Data Row Deleted...");
},
),
],
),
/* onTap: () {
// print("Tapped 'Delete' Action");
debugPrint("Data Row Deleted...");
}, */
),
],
),
)
.toList(),
),
),
),
],
),
),
),
));
}
}
//============================= Services Class Code =================================
class Services {
static const ROOT = 'http://localhost/crm/user_actions.php';
static const String _GET_ACTION = 'GET_ALL';
static const String _ADD_USER_ACTION = 'ADD_USER';
static const String _UPDATE_USER_ACTION = 'UPDATE_USER';
static const String _DELETE_USER_ACTION = 'DELETE_USER';
static Future<List<Users>> getUsers() async {
try {
// var map = new Map<String, dynamic>();
var map = <String, dynamic>{};
map["action"] = _GET_ACTION;
final response = await http.post(Uri.parse(ROOT), body: map);
debugPrint("getUsers >> Response:: ${response.body}");
if (response.statusCode == 200) {
List<Users> list = parsePhotos(response.body);
return list;
} else {
// throw List<Employee>();
throw <Users>[];
}
} catch (e) {
// return List<Employee>();
return <Users>[];
}
}
static List<Users> parsePhotos(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Users>((json) => Users.fromJson(json)).toList();
}
static Future<String> addUser(
String firstName,
String lastName,
) async {
try {
// var map = new Map<String, dynamic>();
var map = <String, dynamic>{};
map["action"] = _ADD_USER_ACTION;
map["firstname"] = firstName;
map["lastname"] = lastName;
final response = await http.post(Uri.parse(ROOT), body: map);
debugPrint("addUser >> Response:: ${response.body}");
return response.body;
} catch (e) {
return 'error';
}
}
static Future<String> updateUser(
/* String userId, */
String firstName,
String lastName,
) async {
try {
// var map = new Map<String, dynamic>();
var map = <String, dynamic>{};
map["action"] = _UPDATE_USER_ACTION;
// map["user_id"] = userId;
map["firstname"] = firstName;
map["lastname"] = lastName;
final response = await http.post(Uri.parse(ROOT), body: map);
debugPrint("deleteUser >> Response:: ${response.body}");
return response.body;
} catch (e) {
return 'error';
}
}
static Future<String> deleteUser(String userId) async {
try {
// var map = new Map<String, dynamic>();
var map = <String, dynamic>{};
map["action"] = _DELETE_USER_ACTION;
map["user_id"] = userId;
final response = await http.post(Uri.parse(ROOT), body: map);
debugPrint("deleteUser >> Response:: ${response.body}");
return response.body;
} catch (e) {
return 'error';
}
}
}
class Users {
String userId;
String firstName;
String lastName;
Users({
required this.userId,
required this.firstName,
required this.lastName,
});
factory Users.fromJson(Map<String, dynamic> json) {
return Users(
userId: json['user_id'],
firstName: json['firstname'] as String,
lastName: json['lastname'] as String,
);
}
}
Here i wrote the code for CRUD operations on Data table with flutter by using php, mysql. Here the Create, Read, Delete functionalities are working fine except update functionality. Actually, i'm trying to get the existing data from one page to another page of texe form fields to update the existing data (which is stored in DB). But, i got
Expected a value of type 'List', but got one of type 'Null'`
Error like this :
I am developing an application with flutter. I set up a singleton structure to access the data in shared preferences. I made a password change area in the settings section of the application. And I wrote the service with node js, everything works fine, but the email value is null.
how can i fix the problem
data_store (singleton)
class DataStore {
static DataStore? _dataStore;
static DataStore? getInstance() {
if (_dataStore == null) {
// keep local instance till it is fully initialized.
var data = DataStore._();
_dataStore = data;
}
return _dataStore;
}
DataStore._();
UserModel user = UserModel();
bool? putUser(UserModel user) {
this.user = user;
return null;
}
UserModel? getUser() {
return user;
}
}
change password page
import 'package:flutter/material.dart';
import 'package:meetdy/Constants/Utils/app_shared_preferences.dart';
import 'package:meetdy/Constants/colors.dart';
import 'package:meetdy/Constants/utils/data_store.dart';
import 'package:meetdy/Models/auth_models/change_passsword_models/change_password_req_model.dart';
import 'package:meetdy/Models/auth_models/user_model.dart';
import 'package:meetdy/Services/auth_services/change_password_services/change_password_services.dart';
import 'package:provider/provider.dart';
import 'package:sizer/sizer.dart';
class ChangePasswordScreen extends StatefulWidget {
const ChangePasswordScreen({Key? key}) : super(key: key);
#override
State<ChangePasswordScreen> createState() => _ChangePasswordScreenState();
}
class _ChangePasswordScreenState extends State<ChangePasswordScreen> {
late Size size = MediaQuery.of(context).size;
bool _isObscure = true;
bool isLoading = false;
final _formKey = GlobalKey<FormState>();
final _passwordController = TextEditingController();
final DataStore? _dataStore = DataStore.getInstance();
UserModel? user;
#override
void initState() {
user = _dataStore?.getUser();
super.initState();
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: GestureDetector(
onTap: () {
FocusManager.instance.primaryFocus?.unfocus();
},
child: Scaffold(
appBar: buildAppBar(context),
body: Padding(
padding: EdgeInsets.symmetric(horizontal: 3.h, vertical: 1.h),
child: Column(
children: [
SizedBox(height: 2.h),
// Login TextFields
Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
children: [
Form(
key: _formKey,
child: TextFormField(
obscureText: _isObscure,
controller: _passwordController,
cursorColor: AppColors.lightBlack,
decoration: InputDecoration(
suffixIcon: IconButton(
icon: Icon(
_isObscure
? Icons.visibility
: Icons.visibility_off,
color: Colors.grey,
),
onPressed: () {
setState(() {
_isObscure = !_isObscure;
});
}),
focusedBorder: InputBorder.none,
enabledBorder: InputBorder.none,
disabledBorder: InputBorder.none,
labelText: 'Password',
labelStyle: TextStyle(
color: AppColors.lightBlack,
),
),
validator: (value) {
if (value!.isEmpty) {
return 'Required';
} else if (value.length < 6) {
return 'Password must be at least 6 characters';
}
return null;
},
onSaved: (value) {
_passwordController.text = value!;
},
),
),
SizedBox(height: 4.h),
Consumer<ChangePasswordService>(
builder: (context, provider, child) {
return Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text(
"Update",
style: TextStyle(
fontSize: 22.sp,
color: AppColors.black,
fontWeight: FontWeight.w300),
),
Padding(
padding:
EdgeInsets.symmetric(horizontal: 1.0.h)),
isLoading
? CircularProgressIndicator(
color: AppColors.orange)
: FloatingActionButton(
backgroundColor: AppColors.orange,
onPressed: () async {
final form = _formKey.currentState;
if (!form!.validate()) {
return;
}
setState(() {
isLoading = true;
});
String password =
_passwordController.text.trim();
String? email = user!.email;
ChangePasswordReqModel passwordData =
ChangePasswordReqModel(
email: email,
password: password);
var newPassword = await provider
.changePassword(passwordData);
setState(() {
isLoading = false;
});
if (newPassword?.error != null) {
var snackBar = SnackBar(
content: Text(
newPassword?.error?.message ??
""),
duration: Duration(seconds: 2),
behavior: SnackBarBehavior.floating,
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(20)),
clipBehavior: Clip.hardEdge,
);
// ignore: use_build_context_synchronously
ScaffoldMessenger.of(context)
.showSnackBar(snackBar);
} else {
var snackBar = SnackBar(
content: Text(
"Your password has been successfully changed"),
duration: Duration(seconds: 2),
behavior: SnackBarBehavior.floating,
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(20)),
clipBehavior: Clip.hardEdge,
);
// ignore: use_build_context_synchronously
ScaffoldMessenger.of(context)
.showSnackBar(snackBar);
}
_passwordController.clear();
},
child: Icon(
Icons.keyboard_arrow_right_sharp))
]);
})
],
),
),
],
),
),
),
),
);
}
AppBar buildAppBar(BuildContext context) {
return AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
centerTitle: true,
title: Text(
"Change Password",
style: TextStyle(
color: AppColors.lightBlack,
),
),
leading: IconButton(
icon: Icon(Icons.arrow_back, color: AppColors.lightBlack),
onPressed: () => Navigator.of(context).pop(),
),
);
}
}
I am developing an audio player application using Flutter, I am using on_audio_query package to get audio files from device storage, and just_audio package for the audio player.
when I created the project, in the audio player I used setState to handle state management, and now, I want to convert to bloc pattern but when I tried to do that I faced a lot of issues and couldn't fix them.
I will attach the code of the audio player and also basic cubit code and if someone guided me or showed me how to convert I would appreciate it.
I'm sorry if the code is confusing but I don't know how to add it correctly.
audio player code
import 'package:just_audio/just_audio.dart';
import 'package:dorosi/shared/ui/my_icon.dart';
import 'package:dorosi/shared/ui/my_text.dart';
import 'package:flutter/material.dart';
import 'package:on_audio_query/on_audio_query.dart';
class AudioPlayerWithUrl extends StatefulWidget {
final SongModel songModel;
const AudioPlayerWithUrl({required this.songModel, Key? key})
: super(key: key);
#override
State<AudioPlayerWithUrl> createState() => _AudioPlayerWithUrlState();
}
class _AudioPlayerWithUrlState extends State<AudioPlayerWithUrl> {
final audioPlayer = AudioPlayer();
bool isPlaying = false;
Duration duration = const Duration();
Duration position = const Duration();
bool isPressed = false;
#override
void initState() {
super.initState();
setAudio();
playAudio();
}
Future setAudio() async {
audioPlayer.setLoopMode(LoopMode.off);
audioPlayer.setAudioSource(
AudioSource.uri(
Uri.parse(widget.songModel.uri!),
),
);
isPlaying = true;
audioPlayer.durationStream.listen((audioDuration) {
setState(() {
duration = audioDuration!;
});
});
audioPlayer.positionStream.listen((audioPosition) {
setState(() {
position = audioPosition;
});
});
}
#override
void dispose() {
audioPlayer.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const MyText(
writtenText: 'Now Playing',
textSize: 23,
textColor: Colors.black,
),
leading: IconButton(
onPressed: () {
Navigator.pop(context);
},
icon: const MyIcon(
icon: Icons.arrow_back,
iconColor: Colors.black,
)),
centerTitle: true,
backgroundColor: Colors.transparent,
elevation: 0,
actions: [
IconButton(
onPressed: () {},
icon: const MyIcon(
icon: Icons.more_vert,
iconColor: Colors.black,
),
),
const SizedBox(width: 10)
],
),
body: SafeArea(
child: SingleChildScrollView(
child: Column(
children: [
const SizedBox(height: 15),
const CircleAvatar(
backgroundColor: Color(0xFFc61104),
radius: 100,
child: MyIcon(
icon: Icons.music_note,
iconSize: 100,
iconColor: Colors.white,
),
),
const SizedBox(
height: 15,
),
const SizedBox(height: 15),
MyText(
writtenText: widget.songModel.title,
textSize: 24,
textWeight: FontWeight.bold,
),
const SizedBox(height: 4),
MyText(
writtenText: widget.songModel.album!,
textSize: 20,
),
const SizedBox(height: 10),
Slider(
activeColor: Colors.orange,
inactiveColor: Colors.black87,
min: 0,
max: duration.inSeconds.toDouble(),
value: position.inSeconds.toDouble(),
onChanged: (value) async {
isPlaying = true;
final position = Duration(seconds: value.toInt());
await audioPlayer.seek(position);
await audioPlayer.play();
}),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
MyText(
writtenText: formatTime(position),
textWeight: FontWeight.bold),
TextButton(
style: TextButton.styleFrom(primary: Colors.black),
onPressed: () {
setState(() {
showRemainingTime();
isPressed = !isPressed;
});
},
child: isPressed
? showRemainingTime()
: MyText(
writtenText: ' ${formatTime(duration)}',
textWeight: FontWeight.bold,
),
),
],
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircleAvatar(
backgroundColor: const Color(0xFFc61104),
radius: 23,
child: IconButton(
onPressed: () async {
if (position >= const Duration(seconds: 10)) {
seekTo(position.inSeconds - 10);
} else {
setState(() {
seekTo(const Duration(seconds: 0).inSeconds);
isPlaying = false;
});
pauseAudio();
}
},
icon: const MyIcon(
icon: Icons.settings_backup_restore,
iconSize: 30,
iconColor: Colors.white,
)),
),
const SizedBox(width: 40),
CircleAvatar(
backgroundColor: const Color(0xFFc61104),
radius: 35,
child: IconButton(
icon: Icon(
isPlaying ? Icons.pause : Icons.play_arrow,
color: Colors.white,
),
iconSize: 50,
onPressed: () {
setState(() {
if (isPlaying) {
pauseAudio();
} else {
playAudio();
}
isPlaying = !isPlaying;
});
},
),
),
const SizedBox(width: 40),
CircleAvatar(
radius: 23,
backgroundColor: const Color(0xFFc61104),
child: IconButton(
onPressed: () async {
if (position < duration - const Duration(seconds: 10)) {
seekTo(position.inSeconds + 10);
} else {
setState(() {
seekTo(duration.inSeconds);
isPlaying = false;
});
pauseAudio();
}
},
icon: const MyIcon(
icon: Icons.forward_10,
iconSize: 30,
iconColor: Colors.white,
)),
),
],
),
const SizedBox(height: 15),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const SizedBox(width: 40),
ElevatedButton(
style: ElevatedButton.styleFrom(primary: Colors.orange),
onPressed: () {
setState(() {
if (audioPlayer.speed == 1) {
adjustAudioSpeed();
debugPrint('${audioPlayer.speed}');
} else if (audioPlayer.speed == 1.25) {
adjustAudioSpeed2();
} else if (audioPlayer.speed == 1.5) {
adjustAudioSpeed3();
} else if (audioPlayer.speed == 1.75) {
adjustAudioSpeed4();
} else if (audioPlayer.speed == 2) {
setAudioNormalSpeed();
}
});
},
child: MyText(
writtenText: '${audioPlayer.speed}',
textSize: 18,
textColor: Colors.black,
)),
const SizedBox(width: 40),
],
)
],
),
)),
);
}
Widget showRemainingTime() {
return MyText(
writtenText: '- ${formatTime(duration - position)}',
textWeight: FontWeight.bold,
);
}
seekTo(int seconds) {
audioPlayer.seek(Duration(seconds: seconds));
}
playAudio() {
audioPlayer.play();
}
pauseAudio() {
audioPlayer.pause();
}
setAudioNormalSpeed() {
audioPlayer.setSpeed(1);
}
adjustAudioSpeed() {
audioPlayer.setSpeed(1.25);
}
adjustAudioSpeed2() {
audioPlayer.setSpeed(1.5);
}
adjustAudioSpeed3() {
audioPlayer.setSpeed(1.75);
}
adjustAudioSpeed4() {
audioPlayer.setSpeed(2);
}
playNextAudio() {
audioPlayer.seekToNext();
}
playPreviousAudio() {
audioPlayer.seekToPrevious();
}
String formatTime(Duration duration) {
String twoDigits(int n) => n.toString().padLeft(2, '0');
final hours = twoDigits(duration.inHours);
final minutes = twoDigits(duration.inMinutes.remainder(60));
final seconds = twoDigits(duration.inSeconds.remainder(60));
return [
if (duration.inHours > 0) hours,
minutes,
seconds,
].join(':');
}
}
player cubit code
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:meta/meta.dart';
part 'player_state.dart';
class PlayerCubit extends Cubit<PlayerState> {
static PlayerCubit get(context) => BlocProvider.of(context);
PlayerCubit() : super(PlayerInitialState());
}
player state code
part of 'player_cubit.dart';
#immutable
abstract class PlayerState {}
class PlayerInitialState extends PlayerState {}
class PlayerPlayingState extends PlayerState {}
class PlayerPauseState extends PlayerState {}
I develop a music player app in flutter, which I use listview builder to list the available music from assets folder, when I run it in debug mode its works proper but when build a release apk, its display a grey color without any content. I develop a music player app in flutter, which I use listview builder to list the available music from assets folder, when I run it in debug mode its works proper but when build a release apk, its display a grey color without any content.
. Below is my complete flutter code
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
import 'durations.dart';
import 'surah.dart';
class PlayList extends StatefulWidget {
const PlayList({Key? key}) : super(key: key);
#override
_PlayListState createState() => _PlayListState();
}
class _PlayListState extends State<PlayList> {
bool isPlaying = false;
bool isPause = false;
bool isRepeat = false;
bool isSheffle = false;
bool isCompleted = false;
Color iconColorR = Colors.white;
Color iconColorS = Colors.white;
int currentSuraIndex = -1;
Duration _position = new Duration();
Duration _musicLength = new Duration();
AudioPlayer _player = AudioPlayer();
PlayerState audioPlayerState = PlayerState.PAUSED;
AudioCache cache = AudioCache();
//PLAY AND PAUSE ICON BUTTON
List<IconData> _icons = [
Icons.play_circle_fill,
Icons.pause_circle_filled
];
List<IconData> _repeateIcons = [
Icons.repeat,
Icons.repeat_one_rounded
];
//FUNCTION THAT FIRED WHEN PROGRAM IS RUN
#override
void initState() {
super.initState();
cache = AudioCache(fixedPlayer: _player);
_player.onDurationChanged.listen((Duration d) {
setState((){
_musicLength = d;
});
});
_player.onAudioPositionChanged.listen((Duration p) {
setState(() {
_position = p;
});
});
_player.onPlayerCompletion.listen((event) {
setState(() {
_position = Duration(seconds: 0);
int rmd = Random().nextInt(112) + 1;
if(isRepeat == true){
isPlaying = true;
} else if(isSheffle == true){
play('quran/${rmd}.mp3');
currentSuraIndex = rmd;
isPlaying = true;
} else {
play('quran/${currentSuraIndex+1}.mp3');
currentSuraIndex++;
}
});
});
}
//FUNTION THAT FIRED WHEN PROGRAM IS CLOSED
#override
void dispose(){
super.dispose();
_player.release();
_player.dispose();
cache.loadedFiles.clear();
}
// PLAY FUNCTION
play(path) async {
await cache.play(path);
}
//FUNCTION THAT CREATE SLIDER
Widget slider(){
return Container(
width: (MediaQuery.of(context).size.width) * 0.7,
child: Slider(
activeColor: Colors.white,
inactiveColor: Colors.grey,
min:0.0,
value: _position.inSeconds.toDouble(),
max: _musicLength.inSeconds.toDouble(),
onChanged: (double value){
setState(() {
seekToSec(value.toInt());
value = value;
});
},
),
);
}
//FUNCTION THAT HANDLE SEEK IN AUDIO
void seekToSec(int sec){
Duration newPosition = Duration(seconds: sec);
_player.seek(newPosition);
}
#override
Widget build(BuildContext context) {
final double screenHeight = MediaQuery.of(context).size.height;
final double screenWidth = MediaQuery.of(context).size.width;
return Scaffold(
appBar: AppBar(
title: Text(
"Surah Index",
style: TextStyle(
fontWeight: FontWeight.bold,
letterSpacing: 7.0,
),
textAlign: TextAlign.right,
),
backgroundColor: Colors.deepOrange.shade900,
foregroundColor: Colors.white,
),
body:Container(
child: ListView.builder(
itemCount: suwaru.length,
itemBuilder: (BuildContext context, int index){
return ListTile(
tileColor: Colors.deepOrangeAccent,
selectedTileColor: Colors.white,
leading: Text('${index+1} ',
style: TextStyle(fontWeight: FontWeight.bold,
color: Colors.white,
fontSize: 20.0
)),
onTap:((){
play('quran/${index}.mp3');
setState(() {
isPlaying = true;
currentSuraIndex = index ;
});
}),
title: Text('${suwaru[index]}',
style: TextStyle(color: Colors.white,
fontWeight: FontWeight.bold,
),
),
subtitle: Text('${durations[index]}',
style: TextStyle(color: Colors.white),
),
trailing: Icon(index==currentSuraIndex&&isPlaying==true?_icons[1]:_icons[0],
color: Colors.white
)
);
}
),
),
bottomNavigationBar: BottomAppBar(
color: Colors.deepOrange.shade900,
child: Container(
height: screenHeight/6,
child: Positioned(
top: 0.0,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
IconButton(
color: iconColorR,
iconSize: 30.0,
onPressed:((){
if(isRepeat == false){
_player.setReleaseMode(ReleaseMode.LOOP);
setState(() {
isRepeat = true;
this.iconColorR = Colors.white;
});
} else if(isRepeat == true){
_player.setReleaseMode(ReleaseMode.RELEASE);
setState(() {
isRepeat = false;
this.iconColorR = Colors.white;
});
}
}),
icon: isRepeat==false?Icon(_repeateIcons[0]):Icon(_repeateIcons[1]),
),
IconButton(
color: Colors.white,
iconSize: 30.0,
onPressed:((){
if(currentSuraIndex>1) {
play('quran/${currentSuraIndex-1}.mp3');
setState(() {
isPlaying = true;
currentSuraIndex--;
});
}else{
play('quran/0.mp3');
}
}),
icon: Icon(Icons.skip_previous_rounded)
),
IconButton(
color: Colors.white,
iconSize: 30.0,
onPressed:((){
if(isPlaying==false) {
play('quran/${currentSuraIndex}.mp3');
setState(() {
isPlaying = true;
});
}else if(isPlaying==true){
_player.pause();
setState(() {
isPlaying = false;
});
}
}),
icon: isPlaying==false?Icon(_icons[0]):Icon(_icons[1]),
),
IconButton(
color: Colors.white,
iconSize: 30.0,
onPressed:((){
if(currentSuraIndex<114) {
play('quran/${currentSuraIndex+1}.mp3');
setState(() {
isPlaying = true;
currentSuraIndex++;
});
}else{
play('quran/0.mp3');
setState(() {
isPlaying = true;
currentSuraIndex = 0;
});
}
}),
icon: Icon(Icons.skip_next_rounded),
),
IconButton(
color: iconColorS,
iconSize: 30.0,
onPressed:((){
print(isSheffle);
if(isSheffle == false ){
setState((){
isSheffle = true;
this.iconColorS = Colors.grey;
});
} else if (isSheffle == true){
setState(() {
isSheffle = false;
this.iconColorS = Colors.white;
});
}
}),
icon: Icon(Icons.shuffle)
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(_position.toString().split('.')[0],
style: TextStyle(color: Colors.white),
),
slider(),
Text(_musicLength.toString().split('.')[0],
style: TextStyle(color: Colors.white),
),
],
),
Text(currentSuraIndex<0?'No Audio Track':'${suwaru[currentSuraIndex].split('(')[0]}',
style: TextStyle(color: Colors.white, fontSize: 10.0,letterSpacing: 5.0,),
),
],
),
),
)
)
);
}
}
I have a screen which shows list of customers using listview. Next when I click on a customer I want to show the notes(records) only of that particular customer(customerId) in next screen in listview. I know how to display all the records of table. but how to display only certain records?? Neither there is any error nor the listview is being displayed. I dont know where am I going wrong.
List<CustomerNote> cnoteList;
int count = 0;
if (cnoteList == null) {
cnoteList = List<CustomerNote>();
updateCustomerNotes();
}
db_service.dart
Future<List<CustomerNote>> getCustomerNotes(int customer) async {
await DB.init();
var res = await DB.rawQuery("noteDetails WHERE custId = '$customer'");
int count = res.length;
List<CustomerNote> cnotelist = List<CustomerNote>();
for (int i = 0; i < count; i++) {
cnotelist.add(CustomerNote.fromMap(res[i]));
}
return cnotelist;
}
People_List.dart //this is the file which displays list of customers
import 'package:customer/models/Note.dart';
import 'package:customer/models/addCustomer.dart';
import 'package:customer/screens/New_Note.dart';
import 'package:customer/screens/Note_info.dart';
import 'package:customer/screens/User_Settings.dart';
import 'package:customer/screens/add_person.dart';
import 'package:customer/services/db_service.dart';
import 'package:customer/utils/database_helper.dart';
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:sqflite/sqflite.dart';
class People_List extends StatefulWidget{
#override
State<StatefulWidget> createState() {
return People_ListState();
}
}
class People_ListState extends State<People_List> with SingleTickerProviderStateMixin{
DBService dbService = DBService();
List<AddCustomer> customerList;
int count = 0;
static final GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();
var _isSelectedItemIndex;
TextEditingController _searchQuery;
bool _isSearching = false;
String searchQuery = "Search query";
#override
void initState() {
super.initState();
_searchQuery = new TextEditingController();
}
void _startSearch() {
print("open search box");
ModalRoute
.of(context)
.addLocalHistoryEntry(new LocalHistoryEntry(onRemove: _stopSearching));
setState(() {
_isSearching = true;
});
}
void _stopSearching() {
_clearSearchQuery();
setState(() {
_isSearching = false;
});
}
void _clearSearchQuery() {
print("close search box");
setState(() {
_searchQuery.clear();
updateSearchQuery("Search query");
});
}
Widget _buildTitle(BuildContext context) {
var horizontalTitleAlignment =
Platform.isIOS ? CrossAxisAlignment.center : CrossAxisAlignment.start;
return new InkWell(
onTap: () => scaffoldKey.currentState.openDrawer(),
child: new Padding(
padding: const EdgeInsets.symmetric(horizontal: 12.0),
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: horizontalTitleAlignment,
children: <Widget>[
const Text(''),
],
),
),
);
}
Widget _buildSearchField() {
return new TextField(
controller: _searchQuery,
autofocus: true,
decoration: const InputDecoration(
hintText: 'Search...',
border: InputBorder.none,
hintStyle: const TextStyle(color: Colors.white30),
),
style: const TextStyle(color: Colors.white, fontSize: 16.0),
onChanged: updateSearchQuery,
);
}
void updateSearchQuery(String newQuery) {
setState(() {
searchQuery = newQuery;
});
print("search query " + newQuery);
}
List<Widget> _buildActions() {
if (_isSearching) {
return <Widget>[
new IconButton(
icon: const Icon(Icons.clear),
onPressed: () {
if (_searchQuery == null || _searchQuery.text.isEmpty) {
Navigator.pop(context);
return;
}
_clearSearchQuery();
},
),
];
}
return <Widget>[
new IconButton(
icon: const Icon(Icons.search),
onPressed: _startSearch,
),
];
}
#override
Widget build(BuildContext context) {
var height = MediaQuery.of(context).size.height;
var width = MediaQuery.of(context).size.width;
if (customerList == null) {
customerList = List<AddCustomer>();
updateListView();
}
return Scaffold(
appBar: new AppBar(
leading: _isSearching ? const BackButton() : null,
title: _isSearching ? _buildSearchField() : _buildTitle(context),
actions: _buildActions(),
),
body:getCustomerListView(),
floatingActionButton: FloatingActionButton(
onPressed: () {
navigateToCustomer(AddCustomer(), 'Add Person');
},
child: const Icon(Icons.add),
),
bottomNavigationBar:Row (
children: <Widget>[
buildNavBarItem(Icons.home,0,"Home"),
buildNavBarItem(Icons.fiber_new_rounded,1,"Upcoming"),
buildNavBarItem(Icons.history,2,"History"),
buildNavBarItem(Icons.account_circle,3,"Account"),
],
),
);
}
ListView getCustomerListView() {
TextStyle titleStyle = Theme.of(context).textTheme.subhead;
return ListView.builder(
itemCount: count,
itemBuilder: (BuildContext context, int position) {
return Card(
color: Colors.white,
elevation: 2.0,
child: ListTile(
/*trailing: CircleAvatar(
backgroundColor: getPriorityColor(this.noteList[position].priority),
child: getPriorityIcon(this.noteList[position].priority),
),*/
title: Text(this.customerList[position].custName, style: titleStyle,),
//subtitle: Text(this.customerList[position].date),
onTap: () {
},
),
);
},
);
}
void navigateToCustomer(AddCustomer customer, String title) async {
bool result = await Navigator.push(context, MaterialPageRoute(builder: (context) {
return AddPerson(customer, title);
}));
if (result == true) {
updateListView();
}
}
void updateListView() {
final Future<Database> dbFuture = DB.init();
dbFuture.then((database) {
Future<List<AddCustomer>> customerListFuture = dbService.getCustomerList();
customerListFuture.then((customerList) {
setState(() {
this.customerList = customerList;
this.count = customerList.length;
});
});
});
}
Widget buildNavBarItem(IconData icon,int index,title) {
var height = MediaQuery.of(context).size.height;
var width = MediaQuery.of(context).size.width;
return GestureDetector(
onTap: () {
setState(() {
_isSelectedItemIndex=index;
if(_isSelectedItemIndex==3) {
Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) => User_Settings()));
}
});
},
child: Container(
height: height * 0.09,
width: width / 4,
decoration: index==_isSelectedItemIndex?BoxDecoration(
border: Border(
bottom: BorderSide(width: 4,color: Theme.of(context).primaryColor),
),
gradient: LinearGradient(colors: [
Theme.of(context).primaryColor.withOpacity(0.3),
Theme.of(context).primaryColor.withOpacity(0.015),
],begin: Alignment.bottomCenter,end: Alignment.topCenter)
):BoxDecoration(),
child: Column(
children: <Widget>[
InkWell(
child: Icon(icon,
color: index==_isSelectedItemIndex? Theme.of(context).primaryColor:Colors.black54,
),
),
Text(title)
],)),
);
}
}
Note_Info.dart
class Note_Info extends StatefulWidget{
final String appBarTitle;
final AddCustomer customer;
Note_Info(this. customer, this.appBarTitle);
#override
State<StatefulWidget> createState() {
return Note_InfoState(this.customer,this.appBarTitle);
}
}
class Note_InfoState extends State<Note_Info> {
CustomerNote note=CustomerNote();
DBService dbService = DBService();
List<CustomerNote> cnoteList;
int count = 0;
String appBarTitle;
AddCustomer customer;
Note_InfoState(this.customer, this.appBarTitle);
PickedFile _imageFile;
final ImagePicker _picker = ImagePicker();
bool rememberMe = false;
DateTime _date = DateTime.now();
TextEditingController custNameController = TextEditingController();
void getImage(ImageSource source) async {
final pickedFile = await _picker.getImage(
source: source);
setState(() {
_imageFile = pickedFile;
});
}
#override
Widget build(BuildContext context) {
if (noteList == null) {
noteList = List<CustomerNote>();
updateCustomerNotes();
}
var height = MediaQuery.of(context).size.height;
custNameController.text = customer.custName;
return DefaultTabController(
length: 4,
child: Scaffold(
appBar: AppBar(
actions: [
IconButton(
icon: Icon(
Icons.add,
),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) => NewNote()));
},
)
],
),
body: Container(
child: Column(
children: <Widget>[
TextField(controller: custNameController,
style: TextStyle(
fontSize: 20.0, fontWeight: FontWeight.bold),
textAlign: TextAlign.center),
Padding(
padding: const EdgeInsets.all(15.0),
child: Row(children: [
ImageProfile(),
Padding(
padding: const EdgeInsets.only(left: 30.0),
child: IconButton(
icon: Icon(
Icons.call,
color: Colors.green,
size: 45,
),
onPressed: () {
},
),
),
],),
),
SizedBox(
height: 50,
child: AppBar(
bottom: TabBar(
tabs: [
Tab(
text: "All",
),
Tab(
text: "Pending",
),
Tab(
text: "Cancelled",
),
Tab(
text: "Completed",
),
],
),
),
),
// create widgets for each tab bar here
Expanded(
child: TabBarView(
children: [
// first tab bar view widget
Container(
child: getNoteListView(),
),
// second tab bar view widget
Container(
child: Center(
child: Text(
'Pending Items',
),
),
),
Container(
child: Center(
child: Text(
'Cancelled',
),
),
),
Container(
child: Center(
child: Text(
'Completed',
),
),
),
],
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: 55.0,
width: 200,
child: RaisedButton(
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
color: Theme
.of(context)
.primaryColorDark,
textColor: Colors.white,
child: Text('Save', textScaleFactor: 1.5,),
onPressed: () {
setState(() {
//_reset();
});
},
),
),
),
]
),
)
));
}
void updateCustomerNotes() {
final Future<Database> dbFuture = DB.init();
dbFuture.then((database) {
int customerId=customer.custId;
Future<List<CustomerNote>> noteListFuture = dbService.getCustomerNotes(customerId);
noteListFuture.then((cnoteList) {
setState(() {
this.cnoteList = cnoteList;
//this.count = cnoteList.length;
});
});
});
}
ListView getNoteListView() {
TextStyle titleStyle = Theme.of(context).textTheme.subhead;
return ListView.builder(
itemCount: count,
itemBuilder: (BuildContext context, int position) {
return Card(
color: Colors.white,
elevation: 2.0,
child: ListTile(
title: Text(this.cnoteList[position].note, style: titleStyle,),
subtitle: Text(this.cnoteList[position].date),
trailing: GestureDetector(
child: Icon(Icons.delete, color: Colors.grey,),
onTap: () {
},
),
onTap: () {
},
),
);
},
);
}
void _showSnackBar(BuildContext context, String message) {
final snackBar = SnackBar(content: Text(message));
Scaffold.of(context).showSnackBar(snackBar);
}
Widget ImageProfile() {
return Center(
child: CircleAvatar(
radius: 80.0,
backgroundImage: AssetImage('images/person_icon.jpg')
),
);
}
}
If u want to get some specific data from the server then you need to provide (where: ) in your query such as
List<Map> result = await db.query(
DatabaseHelper.table,
columns: columnsToSelect,
where: whereString,
whereArgs: whereArguments);
// print the results
result.forEach((row) => print(row));
// {_id: 1, name: Bob, age: 23}
}
Note your query can be different from the above one.
and if you want to get the same specific data from already fetched data then also you need to use the where clause such as
final outData = responseData.where((i) => i.userId == customerId).toList();
and then pass the outData to next page through params.