how to upload a audio from flutter to firebase - android

hello I am working on a app that lets users upload audio from their devices to a account profile. here is the code I have for the profile page:
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:mix/model/MessageData.dart';
import 'package:mix/model/User.dart';
import 'package:mix/services/FirebaseHelper.dart';
import 'package:mix/services/helper.dart';
import 'package:mix/ui/accountDetails/AccountDetailsScreen.dart';
import 'package:mix/ui/auth/AuthScreen.dart';
import 'package:mix/ui/contactUs/ContactUsScreen.dart';
import 'package:mix/ui/fullScreenImageViewer/FullScreenImageViewer.dart';
import 'package:mix/ui/settings/SettingsScreen.dart';
import 'package:mix/ui/upgradeAccount/UpgradeAccount.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:image_picker/image_picker.dart';
import 'package:page_view_indicators/circle_page_indicator.dart';
import '../../constants.dart';
import '../../main.dart';
class ProfileScreen extends StatefulWidget {
final User user;
ProfileScreen({Key key, #required this.user}) : super(key: key);
#override
_ProfileScreenState createState() => _ProfileScreenState(user);
}
class _ProfileScreenState extends State<ProfileScreen> {
final ImagePicker _imagePicker = ImagePicker();
User user;
FireStoreUtils _fireStoreUtils = FireStoreUtils();
final _currentPageNotifier = ValueNotifier<int>(0);
_ProfileScreenState(this.user);
List images = List();
List _pages = [];
List<Widget> _gridPages = [];
#override
void initState() {
images.clear();
images.addAll(user.photos);
if (images.isNotEmpty) {
if (images[images.length - 1] != null) {
images.add(null);
}
} else {
images.add(null);
}
super.initState();
}
#override
Widget build(BuildContext context) {
_gridPages = _buildGridView();
return Scaffold(
body: SingleChildScrollView(
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: <
Widget>[
Padding(
padding: const EdgeInsets.only(top: 16.0, left: 32, right: 32),
child: Stack(
alignment: Alignment.bottomCenter,
children: <Widget>[
Center(
child:
displayCircleImage(user.profilePictureURL, 130, false)),
Positioned(
left: 80,
right: 0,
child: FloatingActionButton(
backgroundColor: Color(COLOR_ACCENT),
child: Icon(
Icons.camera_alt,
color:
isDarkMode(context) ? Colors.black : Colors.white,
),
mini: true,
onPressed: _onCameraClick),
)
],
),
),
Padding(
padding: const EdgeInsets.only(top: 16.0, right: 32, left: 32),
child: SizedBox(
width: double.infinity,
child: Text(
user.fullName(),
style: TextStyle(
color: isDarkMode(context) ? Colors.white : Colors.black,
fontSize: 20),
textAlign: TextAlign.center,
),
),
),
Padding(
padding: const EdgeInsets.only(top: 16.0, left: 16, right: 16),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: skipNulls([
Text(
'My Music',
textAlign: TextAlign.start,
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
_pages.length >= 2
? CirclePageIndicator(
selectedDotColor: Color(COLOR_ACCENT),
dotColor: Colors.grey,
itemCount: _pages.length,
currentPageNotifier: _currentPageNotifier,
)
: null
]),
),
),
Padding(
padding: EdgeInsets.only(top: 16, bottom: 8),
child: SizedBox(
height: user.photos.length > 3 ? 260 : 130,
width: double.infinity,
child: PageView(
children: _gridPages,
onPageChanged: (int index) {
_currentPageNotifier.value = index;
},
)),
),
Column(
children: <Widget>[
ListTile(
dense: true,
onTap: () {
push(context, new AccountDetailsScreen(user: user));
},
title: Text(
'Account Details',
style: TextStyle(fontSize: 16),
),
leading: Icon(
Icons.person,
color: Colors.blue,
),
),
ListTile(
dense: true,
onTap: () {
showModalBottomSheet(
isScrollControlled: true,
context: context,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(
top: Radius.circular(20),
),
),
builder: (context) {
return UpgradeAccount();
},
);
},
title: Text(
user.isVip != null && user.isVip
? 'Cancel subscription'
: 'Upgrade Account',
style: TextStyle(fontSize: 16),
),
leading: Image.asset(
'assets/images/vip.png',
height: 24,
width: 24,
),
),
ListTile(
dense: true,
onTap: () {
push(context, new SettingsScreen(user: user));
},
title: Text(
'Settings',
style: TextStyle(fontSize: 16),
),
leading: Icon(
Icons.settings,
color: isDarkMode(context) ? Colors.white70 : Colors.black45,
),
),
ListTile(
dense: true,
onTap: () {
push(context, new ContactUsScreen());
},
title: Text(
'Contact Us',
style: TextStyle(fontSize: 16),
),
leading: Icon(
Icons.call,
color: Colors.green,
),
),
],
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 24),
child: ConstrainedBox(
constraints: const BoxConstraints(minWidth: double.infinity),
child: FlatButton(
color: Colors.transparent,
child: Text(
'Logout',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: isDarkMode(context) ? Colors.white : Colors.black,
),
),
splashColor: isDarkMode(context)
? Colors.grey[700]
: Colors.grey.shade200,
onPressed: () async {
user.active = false;
user.lastOnlineTimestamp = Timestamp.now();
await FireStoreUtils.updateCurrentUser(user);
await FirebaseAuth.instance.signOut();
MyAppState.currentUser = null;
pushAndRemoveUntil(context, AuthScreen(), false);
},
padding: EdgeInsets.only(top: 12, bottom: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8.0),
side: BorderSide(color: Colors.grey.shade200)),
),
),
),
]),
),
);
}
_onCameraClick() {
final action = CupertinoActionSheet(
message: Text(
"Add profile picture",
style: TextStyle(fontSize: 15.0),
),
actions: <Widget>[
CupertinoActionSheetAction(
child: Text("Remove Picture"),
isDestructiveAction: true,
onPressed: () async {
Navigator.pop(context);
showProgress(context, 'Removing picture...', false);
if (user.profilePictureURL.isNotEmpty)
await _fireStoreUtils.deleteImage(user.profilePictureURL);
user.profilePictureURL = '';
await FireStoreUtils.updateCurrentUser(user);
MyAppState.currentUser = user;
hideProgress();
setState(() {});
},
),
CupertinoActionSheetAction(
child: Text("Choose from gallery"),
onPressed: () async {
Navigator.pop(context);
PickedFile image =
await _imagePicker.getImage(source: ImageSource.gallery);
if (image != null) {
await _imagePicked(File(image.path));
}
setState(() {});
},
),
CupertinoActionSheetAction(
child: Text("Take a picture"),
onPressed: () async {
Navigator.pop(context);
PickedFile image =
await _imagePicker.getImage(source: ImageSource.camera);
if (image != null) {
await _imagePicked(File(image.path));
}
setState(() {});
},
),
],
cancelButton: CupertinoActionSheetAction(
child: Text("Cancel"),
onPressed: () {
Navigator.pop(context);
},
),
);
showCupertinoModalPopup(context: context, builder: (context) => action);
}
Future<void> _imagePicked(File image) async {
showProgress(context, 'Uploading image...', false);
user.profilePictureURL =
await _fireStoreUtils.uploadUserImageToFireStorage(image, user.userID);
await FireStoreUtils.updateCurrentUser(user);
MyAppState.currentUser = user;
hideProgress();
}
Widget _imageBuilder(String url) {
bool isLastItem = url == null;
return GestureDetector(
onTap: () {
isLastItem ? _pickImage() : _viewOrDeleteImage(url);
},
child: Card(
shape: RoundedRectangleBorder(
side: BorderSide.none,
borderRadius: BorderRadius.circular(12),
),
color: Color(COLOR_PRIMARY),
child: isLastItem
? Icon(
Icons.music_note,
size: 50,
color: isDarkMode(context) ? Colors.black : Colors.white,
)
: ClipRRect(
borderRadius: BorderRadius.circular(12),
child: CachedNetworkImage(
fit: BoxFit.cover,
imageUrl:
user.profilePictureURL == DEFAULT_AVATAR_URL ? '' : url,
placeholder: (context, imageUrl) {
return Icon(
Icons.hourglass_empty,
size: 75,
color: isDarkMode(context) ? Colors.black : Colors.white,
);
},
errorWidget: (context, imageUrl, error) {
return Icon(
Icons.error_outline,
size: 75,
color: isDarkMode(context) ? Colors.black : Colors.white,
);
},
),
),
),
);
}
List<Widget> _buildGridView() {
_pages.clear();
List<Widget> gridViewPages = [];
var len = images.length;
var size = 6;
for (var i = 0; i < len; i += size) {
var end = (i + size < len) ? i + size : len;
_pages.add(images.sublist(i, end));
}
_pages.forEach((elements) {
gridViewPages.add(GridView.builder(
padding: EdgeInsets.only(right: 16, left: 16),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
childAspectRatio: 1,
crossAxisSpacing: 10,
mainAxisSpacing: 10),
itemBuilder: (context, index) => _imageBuilder(elements[index]),
itemCount: elements.length,
physics: BouncingScrollPhysics()));
});
return gridViewPages;
}
_viewOrDeleteImage(String url) {
final action = CupertinoActionSheet(
actions: <Widget>[
CupertinoActionSheetAction(
onPressed: () async {
Navigator.pop(context);
images.removeLast();
images.remove(url);
await _fireStoreUtils.deleteImage(url);
user.photos = images;
User newUser =
await FireStoreUtils.updateCurrentUser(user);
MyAppState.currentUser = newUser;
user = newUser;
images.add(null);
setState(() {});
},
child: Text("Remove Picture"),
isDestructiveAction: true,
),
CupertinoActionSheetAction(
onPressed: () {
Navigator.pop(context);
push(context, FullScreenImageViewer(imageUrl: url));
},
isDefaultAction: true,
child: Text("View Picture"),
),
CupertinoActionSheetAction(
onPressed: () async {
Navigator.pop(context);
user.profilePictureURL = url;
user = await FireStoreUtils.updateCurrentUser(user);
setState(() {});
},
isDefaultAction: true,
child: Text("Make Profile Picture"),
)
],
cancelButton: CupertinoActionSheetAction(
child: Text("Cancel"),
onPressed: () {
Navigator.pop(context);
},
),
);
showCupertinoModalPopup(context: context, builder: (context) => action);
}
_pickImage() {
final action = CupertinoActionSheet(
message: Text(
"Add picture",
style: TextStyle(fontSize: 15.0),
),
actions: <Widget>[
CupertinoActionSheetAction(
child: Text("Choose from Files"),
isDefaultAction: false,
onPressed: () async {
Navigator.pop(context);
PickedFile image =
await _imagePicker.getImage(source: ImageSource.gallery);
if (image != null) {
Url imageUrl = await _fireStoreUtils.uploadChatImageToFireStorage(
File(image.path), context);
images.removeLast();
images.add(imageUrl.url);
user.photos = images;
User newUser =
await FireStoreUtils.updateCurrentUser(user);
MyAppState.currentUser = newUser;
user = newUser;
images.add(null);
setState(() {});
}
},
),
CupertinoActionSheetAction(
child: Text("Take a picture"),
isDestructiveAction: false,
onPressed: () async {
Navigator.pop(context);
PickedFile image =
await _imagePicker.getImage(source: ImageSource.camera);
if (image != null) {
Url imageUrl = await _fireStoreUtils.uploadChatImageToFireStorage(
File(image.path), context);
images.removeLast();
images.add(imageUrl.url);
user.photos = images;
User newUser =
await FireStoreUtils.updateCurrentUser(user);
MyAppState.currentUser = newUser;
user = newUser;
images.add(null);
setState(() {});
}
},
)
],
cancelButton: CupertinoActionSheetAction(
child: Text("Cancel"),
onPressed: () {
Navigator.pop(context);
},
),
);
showCupertinoModalPopup(context: context, builder: (context) => action);
}
#override
void dispose() {
_currentPageNotifier.dispose();
super.dispose();
}
}
any ideas on how to add a upload audio function to the my music section of the code?
any help is greatly appreciated. I'm still fairly new to flutter so please go easy on me :)
Thanks in advance!

first add the following packages:
firebase_storage:
gx_file_picker:
File file;//declare this
//on file choose button call this
try {
f = await FilePicker.getFile(
type: FileType.audio,
);
setState(() {
});
}catch(e){
//handle exception
}}
on your button on pressed event
onPressed:(){
upload(file);
}
upload(File fil)async{
String fileName = fil.path
.split('/')
.last;
StorageReference firebaseStorageRef =
FirebaseStorage.instance.ref().child('uploads/$fileName');
StorageUploadTask uploadTask = firebaseStorageRef.putFile(fil);
StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
taskSnapshot.ref.getDownloadURL().then(
(value) {
});
}

Related

How to show list of images in grid view builder if list is not empty

i have a list which contains list of images, i want to show these in my grid view builder if list if not empty other wise i just want to show static + symbol in my grid view builder.
it is my list
var otherPersonOfferList = <Inventory>[].obs;
and this is my grid view builder which i have extracted as a widget and using it in my screen
import 'package:bartermade/models/Get_Inventory.dart';
import 'package:bartermade/models/inventory.dart';
import 'package:bartermade/widgets/inventoryTile.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controllers/inventoryController.dart';
class OfferGrid extends StatefulWidget {
OfferGrid(
{Key? key,
required this.list,
required this.modelSheetHeading,
required this.gestureState})
: super(key: key);
String modelSheetHeading;
List<Inventory> list;
bool gestureState;
#override
State<OfferGrid> createState() => _OfferGridState();
}
class _OfferGridState extends State<OfferGrid> {
InventoryController inventoryController = Get.find();
bool isDeleting = false;
#override
Widget build(BuildContext context) {
if (widget.gestureState == true
? (inventoryController.otherPersonOfferList == [] ||
inventoryController.otherPersonOfferList.length == 0 ||
inventoryController.otherPersonOfferList.isEmpty)
: (inventoryController.myOfferList == [] ||
inventoryController.myOfferList.length == 0 ||
inventoryController.myOfferList.isEmpty)) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: GestureDetector(
onTap: () {
showModalBottomSheet(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
context: context,
builder: (context) {
return InventoryTile(
modelSheetHeading: widget.modelSheetHeading,
list: widget.gestureState == true
? inventoryController.traderInventoryList
: inventoryController.myInventoryList1,
inventoryController: inventoryController,
gestureState: widget.gestureState);
});
},
child: Container(
height: 90,
width: 90,
decoration: BoxDecoration(border: Border.all(color: Colors.black)),
child: Icon(
Icons.add,
size: 35,
),
),
),
);
} else {
return GridView.builder(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemCount: widget.list.length + 1,
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
itemBuilder: (context, index) {
if (index == widget.list.length) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: GestureDetector(
onTap: () {
showModalBottomSheet(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
context: context,
builder: (context) {
return InventoryTile(
modelSheetHeading: widget.modelSheetHeading,
list: widget.gestureState == true
? inventoryController.traderInventoryList
: inventoryController.myInventoryList1,
inventoryController: inventoryController,
gestureState: widget.gestureState);
});
},
child: Container(
height: 30,
width: 30,
decoration:
BoxDecoration(border: Border.all(color: Colors.black)),
child: Icon(
Icons.add,
size: 35,
),
),
),
);
} else {
return Stack(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: GestureDetector(
onLongPress: () {
setState(() {
isDeleting = true;
});
},
onTap : (){
setState(() {
isDeleting = false;
});
},
child: CachedNetworkImage(
fit: BoxFit.cover,
height: 100,
width: 200,
imageUrl: // "https://asia-exstatic-vivofs.vivo.com/PSee2l50xoirPK7y/1642733614422/0ae79529ef33f2b3eb7602f89c1472b3.jpg"
"${widget.list[index].url}",
placeholder: (context, url) => Center(
child: CircularProgressIndicator(
color: Colors.grey,
),
),
errorWidget: (context, url, error) => Icon(Icons.error),
),
),
),
isDeleting == true
? Positioned(
right: 0,
top: 0,
child: CircleAvatar(
backgroundColor: Colors.red,
radius: 10,
child: Icon(
Icons.remove,
size: 14,
),
),
)
: SizedBox()
],
);
}
});
}
}
}
and this is my screen where is just want to check if my list is non empty then fill my grid view with images otherwise just show + sign in grid view
import 'package:bartermade/controllers/inventoryController.dart';
import 'package:bartermade/models/Get_Inventory.dart';
import 'package:bartermade/models/inventory.dart';
import 'package:bartermade/screens/chat/chatScreen.dart';
import 'package:bartermade/utils/app_colors.dart';
import 'package:bartermade/widgets/snackBar.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import '../../../../services/inventoryService.dart';
import '../../../../widgets/offerGrid.dart';
class OfferTradeScreen extends StatefulWidget {
String postUserId;
String postUserName;
OfferTradeScreen({
Key? key,
required this.postUserId,
required this.postUserName,
}) : super(key: key);
#override
State<OfferTradeScreen> createState() => _OfferTradeScreenState();
}
class _OfferTradeScreenState extends State<OfferTradeScreen> {
// TradeController tradeController = Get.put(TradeController());
InventoryController inventoryController = Get.put(InventoryController());
// GiftStorageService giftStorageService = GiftStorageService();
// GiftController giftController = Get.put(GiftController());
// ProfileController profileController = Get.put(ProfileController());
// TradeStorageService tradeStorageService = TradeStorageService();
// TradingService tradingService = TradingService();
// PreferenceService preferenceService = PreferenceService();
late List<Inventory> otherPersonList;
late List<Inventory> myList;
#override
void initState() {
super.initState();
inventoryController.getOtherUserInventory(widget.postUserId);
otherPersonList = inventoryController.otherPersonOfferList;
myList = inventoryController.myOfferList;
}
otherPersonlistener() {
inventoryController.otherPersonOfferList.listen((p0) {
if (this.mounted) {
setState(() {
otherPersonList = p0;
});
}
});
}
mylistener() {
inventoryController.myOfferList.listen((p0) {
if (this.mounted) {
setState(() {
myList = p0;
});
}
});
}
int draggableIndex = 0;
#override
Widget build(BuildContext context) {
print("-------building------");
otherPersonlistener();
mylistener();
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
return Scaffold(
appBar: AppBar(
titleSpacing: 0,
leading: GestureDetector(
onTap: () {
inventoryController.myOfferList.clear();
inventoryController.otherPersonOfferList.clear();
Get.back();
},
child: Icon(Icons.arrow_back)),
title: Text(
"Offer",
style: TextStyle(color: Colors.white),
),
actions: [
Padding(
padding: const EdgeInsets.only(right: 15),
child: GestureDetector(
onTap: () {
Get.to(() => ChatScreen(
currentUserId: widget.postUserId,
recieverId: inventoryController.userId.toString()));
},
child: Icon(Icons.message)),
)
],
),
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
flex: 10,
child: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(top: 20),
child: Text(
"${widget.postUserName} Inventory",
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontWeight: FontWeight.w400),
),
),
OfferGrid(
gestureState: true,
list: otherPersonList,
modelSheetHeading: "${widget.postUserName}",
)
],
),
),
),
Expanded(
flex: 1,
child: Divider(
thickness: 2,
color: Colors.black,
height: 3,
),
),
Expanded(
flex: 10,
child: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"My Inventory",
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontWeight: FontWeight.w400),
),
OfferGrid(
gestureState: false,
list: myList,
modelSheetHeading: "My Inventory",
)
],
),
),
),
Center(child: Obx(() {
return inventoryController.makingOffer.value == true
? CircularProgressIndicator(
color: AppColors.pinkAppBar,
)
: ElevatedButton(
onPressed: () {
if (inventoryController.otherPersonOfferList.isEmpty &&
inventoryController.myOfferList.isEmpty) {
showSnackBar(
"Please add both inventories to make offer",
context);
} else {
inventoryController.postOffer(
widget.postUserId, context);
}
},
style: ElevatedButton.styleFrom(
padding: EdgeInsets.symmetric(
vertical: 10, horizontal: 50)),
child: Text("Send Offer"));
}))
],
),
),
);
}
#override
void dispose() {
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeRight,
DeviceOrientation.landscapeLeft,
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
super.dispose();
}
}
User following code :
GridView.builder(
shrinkWrap: true,
itemCount: data.length,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 17,
mainAxisSpacing: 17,
),
itemBuilder: (
context,
index,
) {
return Obx(
() => InkWell(
onTap: () {
},
child: ClipRRect(
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: ColorConfig.colorDarkBlue, width: 2),
image: DecorationImage(
image: AssetImage(ImagePath.unselectedContainer), ///imageURL
fit: BoxFit.fill,
)),
child: Center(
child: Text(data[index].heading,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: ThemeConstants.textThemeFontSize18,
fontWeight: FontWeight.w700,
color: ColorConfig.colorDarkBlue)),
),
height: 150,
),
),
),
);
},
),

How detect a change on state of flutter widget

I need to detect when my phoneCall variable changes state this to detect when the call ended and show a modal to the user so he can rate the call. This is the widget code.
import 'dart:convert';
import 'package:avanx/flutter/loading_view.dart';
import 'package:avanx/globals.dart';
import 'package:avanx/models/group.dart';
import 'package:avanx/models/prospect.dart';
import 'package:cool_alert/cool_alert.dart';
import 'package:flutter_phone_state/flutter_phone_state.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:url_launcher/url_launcher.dart';
import '../flutter/theme.dart';
import 'package:avanx/flutter/input_widget.dart';
import '../flutter/widgets.dart';
import 'package:flutter/material.dart';
import 'package:avanx/flutter/drawer_widget.dart';
import 'package:loading_animations/loading_animations.dart';
import 'package:http/http.dart' as http;
class LeadsHomeWidget extends StatefulWidget {
LeadsHomeWidget({Key key}) : super(key: key);
#override
_LeadsHomeWidgetState createState() => _LeadsHomeWidgetState();
}
class _LeadsHomeWidgetState extends State<LeadsHomeWidget> {
List<dynamic> _leads = [];
List<dynamic> _groups;
var phoneCall;
TextEditingController textController;
final scaffoldKey = GlobalKey<ScaffoldState>();
GlobalKey<FormState> _formKey = GlobalKey();
String _search = '';
_initCall(_number) async {
setState(() {
phoneCall = FlutterPhoneState.startPhoneCall(_number);
});
}
showCallInfo() {
print(phoneCall
.status); // ringing, dialing, cancelled, error, connecting, connected, timedOut, disconnected
print(phoneCall.isComplete); // Whether the call is complete
print(phoneCall
.events); // A list of call events related to this specific call
}
// Metodo para la obtención de los grupos existentes.
getGroups() async {
print("hello");
final response = await http.get(Uri.parse(Globals.avanx + '/groups'),
headers: {"Accept": "application/json"});
if (response.statusCode == 200) {
var groupsList = json.decode(response.body)['groups'];
List<dynamic> groups =
groupsList.map((element) => new Group.fromJson(element)).toList();
setState(() {
_groups = groups;
});
} else {
throw Exception('Failed to load groups');
}
}
getLeads(name) async {
if (name != '') {
String auth = Globals.authUser.user.id.toString();
final response = await http.post(
Uri.parse(Globals.avanx + '/prospects/search/$auth'),
body: {'name': name},
headers: {"Accept": "application/json"});
if (response.statusCode == 200) {
var leadsList = json.decode(response.body)['leads'];
List<dynamic> leads =
leadsList.map((element) => new Prospect.fromJson(element)).toList();
setState(() {
_leads = leads;
});
} else {
throw Exception('Failed to load leads');
}
} else {
setState(() {
_leads = [];
});
}
}
deleteModal(id) {
CoolAlert.show(
context: context,
animType: null,
type: CoolAlertType.warning,
title: '¿Estas Seguro?',
text: "Esta acción no se puede reversar.",
backgroundColor: Color(0xBF35126A),
confirmBtnText: 'Confirmar',
confirmBtnColor: Color(0xBF35126A),
showCancelBtn: true,
cancelBtnText: 'Cancelar',
onConfirmBtnTap: () {
deleteLead(id);
Navigator.pop(context);
});
}
deleteLead(id) async {
final response = await http.delete(
Uri.parse(Globals.avanx + '/prospects/$id'),
headers: {"Accept": "application/json"});
if (response.statusCode == 200) {
_search = '';
this.getLeads(_search);
} else {
throw Exception('Failed to load leads');
}
}
#override
void initState() {
textController = TextEditingController();
this.getGroups();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
key: scaffoldKey,
backgroundColor: FlutterTheme.tertiaryColor,
appBar: AppBar(
backgroundColor: FlutterTheme.primaryColor,
title: Text(
'Prospectos',
style: TextStyle(fontFamily: 'Montserrat'),
),
centerTitle: true,
),
drawer: DrawerWidget(),
body: _groups == null
? LoadingWidget()
: Align(
alignment: Alignment(0, 0),
child: Padding(
padding: EdgeInsets.fromLTRB(30, 10, 30, 0),
child: ListView(
padding: EdgeInsets.zero,
scrollDirection: Axis.vertical,
children: _groups == null
? []
: [
Form(
key: _formKey,
child: Row(
children: [
Expanded(
flex: 2,
child: Container(
padding:
EdgeInsets.symmetric(horizontal: 15),
child: InputWidget(
label: 'Buscar prospecto?',
keyBoardType: TextInputType.text,
onChanged: (text) {
_search = text;
},
validator: (text) {
if (text.trim().length == 0) {
return "input data";
}
return null;
},
),
),
),
Expanded(
child: ElevatedButton(
child: Text(
'Buscar',
style: TextStyle(
color: FlutterTheme.primaryColor),
),
onPressed: () {
getLeads(_search);
},
style: ElevatedButton.styleFrom(
side: BorderSide(
width: 1.5,
color: FlutterTheme.primaryColor,
),
primary: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30),
),
),
),
),
],
),
),
phoneCall.isComplete
? Container(
child: Text('The call is end!!'),
)
: Container(),
for (var lead in _leads ?? [])
Padding(
padding: const EdgeInsets.symmetric(vertical: 10),
child: Slidable(
actionPane: SlidableDrawerActionPane(),
actionExtentRatio: 0.25,
child: Container(
color: Colors.white,
child: ListTile(
leading: CircleAvatar(
backgroundImage: NetworkImage(
'https://ui-avatars.com/api/?name=' +
lead.name +
'&background=35126A&color=fff&size=128'),
),
title: Text(lead.name),
subtitle: Text(
'Grupo: ' + lead.group.name,
style: TextStyle(fontSize: 11),
),
trailing: Container(
width: 100,
child: Row(
children: [
IconButton(
onPressed: () {
_initCall(lead.phone);
},
icon: Icon(
Icons.phone,
size: 35,
color: Color(0xFF35126A),
)),
IconButton(
onPressed: () {
showCallInfo();
},
icon: Icon(
Icons.mail_outline,
size: 35,
color: Color(0xFF35126A),
)),
],
),
),
),
),
secondaryActions: <Widget>[
IconSlideAction(
onTap: () {
Navigator.pushNamed(context, 'leads_edit',
arguments: lead);
},
caption: 'Edit',
color: Color(0xFF35126A),
icon: Icons.edit,
),
IconSlideAction(
onTap: () {
deleteModal(lead.id);
},
caption: 'Delete',
color: Colors.red,
icon: Icons.delete,
),
],
),
),
Padding(
padding: EdgeInsets.fromLTRB(0, 40, 0, 0),
child: ButtonWidget(
onPressed: () {
Navigator.pushNamed(context, 'leads_add_new');
},
text: 'Agregar Nuevo',
options: ButtonOptions(
width: 130,
height: 40,
color: FlutterTheme.tertiaryColor,
textStyle: FlutterTheme.subtitle2.override(
fontFamily: 'Montserrat',
color: FlutterTheme.primaryColor,
),
borderSide: BorderSide(
color: FlutterTheme.primaryColor,
width: 2,
),
borderRadius: 30,
),
),
),
Padding(
padding: EdgeInsets.fromLTRB(0, 40, 0, 0),
child: Text(
'Grupos',
textAlign: TextAlign.center,
style: FlutterTheme.bodyText1.override(
fontFamily: 'Montserrat',
color: Color(0xBF35126A),
fontSize: 20,
),
),
),
for (var group in _groups)
Padding(
padding: EdgeInsets.fromLTRB(0, 20, 0, 0),
child: ButtonWidget(
onPressed: () {
Navigator.pushNamed(context, 'leads_list',
arguments: group);
},
text: group.name,
options: ButtonOptions(
width: 130,
height: 40,
color: FlutterTheme.primaryColor,
textStyle: FlutterTheme.subtitle2.override(
fontFamily: 'Montserrat',
color: Colors.white,
),
borderSide: BorderSide(
color: Colors.transparent,
width: 1,
),
borderRadius: 30,
),
),
),
],
),
),
),
);
}
}
The function _initCall is the one in charge of initializing the call, so the variable phoneCall will have the information of the state of the call, I want to launch a modal when the call finishes.

error when adding gx_file_picker to a picker sheet in flutter app

hello I am working on a app that lets users upload audio from their devices to a account profile. I am getting a error when trying to create the upload audio action card.
here is the error I'm getting:
Positional arguments must occur before named arguments. Try moving
all of the positional arguments before the named arguments. Too many
positional arguments: 0 expected, but 2 found. Try removing the extra
positional arguments, or specifying the name for named arguments. Open
documentation
the error is on this line of code:
File file;
here is the code I have for the profile page:
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:gx_file_picker/gx_file_picker.dart';
import 'package:mix/model/MessageData.dart';
import 'package:mix/model/User.dart';
import 'package:mix/services/FirebaseHelper.dart';
import 'package:mix/services/helper.dart';
import 'package:mix/ui/accountDetails/AccountDetailsScreen.dart';
import 'package:mix/ui/auth/AuthScreen.dart';
import 'package:mix/ui/contactUs/ContactUsScreen.dart';
import 'package:mix/ui/fullScreenImageViewer/FullScreenImageViewer.dart';
import 'package:mix/ui/settings/SettingsScreen.dart';
import 'package:mix/ui/upgradeAccount/UpgradeAccount.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:image_picker/image_picker.dart';
import 'package:page_view_indicators/circle_page_indicator.dart';
import '../../constants.dart';
import '../../main.dart';
class ProfileScreen extends StatefulWidget {
final User user;
ProfileScreen({Key key, #required this.user}) : super(key: key);
#override
_ProfileScreenState createState() => _ProfileScreenState(user);
}
class _ProfileScreenState extends State<ProfileScreen> {
final ImagePicker _imagePicker = ImagePicker();
User user;
FireStoreUtils _fireStoreUtils = FireStoreUtils();
final _currentPageNotifier = ValueNotifier<int>(0);
_ProfileScreenState(this.user);
List images = List();
List _pages = [];
List<Widget> _gridPages = [];
#override
void initState() {
images.clear();
images.addAll(user.photos);
if (images.isNotEmpty) {
if (images[images.length - 1] != null) {
images.add(null);
}
} else {
images.add(null);
}
super.initState();
}
#override
Widget build(BuildContext context) {
_gridPages = _buildGridView();
return Scaffold(
body: SingleChildScrollView(
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: <
Widget>[
Padding(
padding: const EdgeInsets.only(top: 16.0, left: 32, right: 32),
child: Stack(
alignment: Alignment.bottomCenter,
children: <Widget>[
Center(
child:
displayCircleImage(user.profilePictureURL, 130, false)),
Positioned(
left: 80,
right: 0,
child: FloatingActionButton(
backgroundColor: Color(COLOR_ACCENT),
child: Icon(
Icons.camera_alt,
color:
isDarkMode(context) ? Colors.black : Colors.white,
),
mini: true,
onPressed: _onCameraClick),
)
],
),
),
Padding(
padding: const EdgeInsets.only(top: 16.0, right: 32, left: 32),
child: SizedBox(
width: double.infinity,
child: Text(
user.fullName(),
style: TextStyle(
color: isDarkMode(context) ? Colors.white : Colors.black,
fontSize: 20),
textAlign: TextAlign.center,
),
),
),
Padding(
padding: const EdgeInsets.only(top: 16.0, left: 16, right: 16),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: skipNulls([
Text(
'My Music',
textAlign: TextAlign.start,
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
_pages.length >= 2
? CirclePageIndicator(
selectedDotColor: Color(COLOR_ACCENT),
dotColor: Colors.grey,
itemCount: _pages.length,
currentPageNotifier: _currentPageNotifier,
)
: null
]),
),
),
Padding(
padding: EdgeInsets.only(top: 16, bottom: 8),
child: SizedBox(
height: user.photos.length > 3 ? 260 : 130,
width: double.infinity,
child: PageView(
children: _gridPages,
onPageChanged: (int index) {
_currentPageNotifier.value = index;
},
)),
),
Column(
children: <Widget>[
ListTile(
dense: true,
onTap: () {
push(context, new AccountDetailsScreen(user: user));
},
title: Text(
'Account Details',
style: TextStyle(fontSize: 16),
),
leading: Icon(
Icons.person,
color: Colors.blue,
),
),
ListTile(
dense: true,
onTap: () {
showModalBottomSheet(
isScrollControlled: true,
context: context,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(
top: Radius.circular(20),
),
),
builder: (context) {
return UpgradeAccount();
},
);
},
title: Text(
user.isVip != null && user.isVip
? 'Cancel subscription'
: 'Upgrade Account',
style: TextStyle(fontSize: 16),
),
leading: Image.asset(
'assets/images/vip.png',
height: 24,
width: 24,
),
),
ListTile(
dense: true,
onTap: () {
push(context, new SettingsScreen(user: user));
},
title: Text(
'Settings',
style: TextStyle(fontSize: 16),
),
leading: Icon(
Icons.settings,
color: isDarkMode(context) ? Colors.white70 : Colors.black45,
),
),
ListTile(
dense: true,
onTap: () {
push(context, new ContactUsScreen());
},
title: Text(
'Contact Us',
style: TextStyle(fontSize: 16),
),
leading: Icon(
Icons.call,
color: Colors.green,
),
),
],
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 24),
child: ConstrainedBox(
constraints: const BoxConstraints(minWidth: double.infinity),
child: FlatButton(
color: Colors.transparent,
child: Text(
'Logout',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: isDarkMode(context) ? Colors.white : Colors.black,
),
),
splashColor: isDarkMode(context)
? Colors.grey[700]
: Colors.grey.shade200,
onPressed: () async {
user.active = false;
user.lastOnlineTimestamp = Timestamp.now();
await FireStoreUtils.updateCurrentUser(user);
await FirebaseAuth.instance.signOut();
MyAppState.currentUser = null;
pushAndRemoveUntil(context, AuthScreen(), false);
},
padding: EdgeInsets.only(top: 12, bottom: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8.0),
side: BorderSide(color: Colors.grey.shade200)),
),
),
),
]),
),
);
}
_onCameraClick() {
final action = CupertinoActionSheet(
message: Text(
"Add profile picture",
style: TextStyle(fontSize: 15.0),
),
actions: <Widget>[
CupertinoActionSheetAction(
child: Text("Remove Picture"),
isDestructiveAction: true,
onPressed: () async {
Navigator.pop(context);
showProgress(context, 'Removing picture...', false);
if (user.profilePictureURL.isNotEmpty)
await _fireStoreUtils.deleteImage(user.profilePictureURL);
user.profilePictureURL = '';
await FireStoreUtils.updateCurrentUser(user);
MyAppState.currentUser = user;
hideProgress();
setState(() {});
},
),
CupertinoActionSheetAction(
child: Text("Choose from gallery"),
onPressed: () async {
Navigator.pop(context);
PickedFile image =
await _imagePicker.getImage(source: ImageSource.gallery);
if (image != null) {
await _imagePicked(File(image.path));
}
setState(() {});
},
),
CupertinoActionSheetAction(
child: Text("Take a picture"),
onPressed: () async {
Navigator.pop(context);
PickedFile image =
await _imagePicker.getImage(source: ImageSource.camera);
if (image != null) {
await _imagePicked(File(image.path));
}
setState(() {});
},
),
],
cancelButton: CupertinoActionSheetAction(
child: Text("Cancel"),
onPressed: () {
Navigator.pop(context);
},
),
);
showCupertinoModalPopup(context: context, builder: (context) => action);
}
Future<void> _imagePicked(File image) async {
showProgress(context, 'Uploading image...', false);
user.profilePictureURL =
await _fireStoreUtils.uploadUserImageToFireStorage(image, user.userID);
await FireStoreUtils.updateCurrentUser(user);
MyAppState.currentUser = user;
hideProgress();
}
Widget _imageBuilder(String url) {
bool isLastItem = url == null;
return GestureDetector(
onTap: () {
isLastItem ? _pickAudio() : _viewOrDeleteImage(url);
},
child: Card(
shape: RoundedRectangleBorder(
side: BorderSide.none,
borderRadius: BorderRadius.circular(12),
),
color: Color(COLOR_PRIMARY),
child: isLastItem
? Icon(
Icons.music_note,
size: 50,
color: isDarkMode(context) ? Colors.black : Colors.white,
)
: ClipRRect(
borderRadius: BorderRadius.circular(12),
child: CachedNetworkImage(
fit: BoxFit.cover,
imageUrl:
user.profilePictureURL == DEFAULT_AVATAR_URL ? '' : url,
placeholder: (context, imageUrl) {
return Icon(
Icons.hourglass_empty,
size: 75,
color: isDarkMode(context) ? Colors.black : Colors.white,
);
},
errorWidget: (context, imageUrl, error) {
return Icon(
Icons.error_outline,
size: 75,
color: isDarkMode(context) ? Colors.black : Colors.white,
);
},
),
),
),
);
}
List<Widget> _buildGridView() {
_pages.clear();
List<Widget> gridViewPages = [];
var len = images.length;
var size = 6;
for (var i = 0; i < len; i += size) {
var end = (i + size < len) ? i + size : len;
_pages.add(images.sublist(i, end));
}
_pages.forEach((elements) {
gridViewPages.add(GridView.builder(
padding: EdgeInsets.only(right: 16, left: 16),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
childAspectRatio: 1,
crossAxisSpacing: 10,
mainAxisSpacing: 10),
itemBuilder: (context, index) => _imageBuilder(elements[index]),
itemCount: elements.length,
physics: BouncingScrollPhysics()));
});
return gridViewPages;
}
_viewOrDeleteImage(String url) {
final action = CupertinoActionSheet(
actions: <Widget>[
CupertinoActionSheetAction(
onPressed: () async {
Navigator.pop(context);
images.removeLast();
images.remove(url);
await _fireStoreUtils.deleteImage(url);
user.photos = images;
User newUser =
await FireStoreUtils.updateCurrentUser(user);
MyAppState.currentUser = newUser;
user = newUser;
images.add(null);
setState(() {});
},
child: Text("Remove Picture"),
isDestructiveAction: true,
),
CupertinoActionSheetAction(
onPressed: () {
Navigator.pop(context);
push(context, FullScreenImageViewer(imageUrl: url));
},
isDefaultAction: true,
child: Text("View Picture"),
),
CupertinoActionSheetAction(
onPressed: () async {
Navigator.pop(context);
user.profilePictureURL = url;
user = await FireStoreUtils.updateCurrentUser(user);
setState(() {});
},
isDefaultAction: true,
child: Text("Make Profile Picture"),
)
],
cancelButton: CupertinoActionSheetAction(
child: Text("Cancel"),
onPressed: () {
Navigator.pop(context);
},
),
);
showCupertinoModalPopup(context: context, builder: (context) => action);
}
_pickImage() {
final action = CupertinoActionSheet(
message: Text(
"Add picture",
style: TextStyle(fontSize: 15.0),
),
actions: <Widget>[
CupertinoActionSheetAction(
child: Text("Choose from Files"),
isDefaultAction: false,
onPressed: () async {
Navigator.pop(context);
PickedFile image =
await _imagePicker.getImage(source: ImageSource.gallery);
if (image != null) {
Url imageUrl = await _fireStoreUtils.uploadChatImageToFireStorage(
File(image.path), context);
images.removeLast();
images.add(imageUrl.url);
user.photos = images;
User newUser =
await FireStoreUtils.updateCurrentUser(user);
MyAppState.currentUser = newUser;
user = newUser;
images.add(null);
setState(() {});
}
},
),
CupertinoActionSheetAction(
child: Text("Take a picture"),
isDestructiveAction: false,
onPressed: () async {
Navigator.pop(context);
PickedFile image =
await _imagePicker.getImage(source: ImageSource.camera);
if (image != null) {
Url imageUrl = await _fireStoreUtils.uploadChatImageToFireStorage(
File(image.path), context);
images.removeLast();
images.add(imageUrl.url);
user.photos = images;
User newUser =
await FireStoreUtils.updateCurrentUser(user);
MyAppState.currentUser = newUser;
user = newUser;
images.add(null);
setState(() {});
}
},
)
],
cancelButton: CupertinoActionSheetAction(
child: Text("Cancel"),
onPressed: () {
Navigator.pop(context);
},
),
);
showCupertinoModalPopup(context: context, builder: (context) => action);
}
//here is the code in question
_pickAudio() {
final action = CupertinoActionSheet(
message: Text(
"Add Audio",
style: TextStyle(fontSize: 15.0),
),
actions: <Widget>[
CupertinoActionSheetAction(
child: Text("Choose from Files"),
isDefaultAction: false,
File file;// error is here
//on file choose button call this
try {
f = await FilePicker.getFile(
type: FileType.audio,
);
setState(() {
});
}catch(e){
//handle exception
}}
onPressed:(){
upload(file);
}
upload(File fil)async{
String fileName = fil.path
.split('/')
.last;
StorageReference firebaseStorageRef =
FirebaseStorage.instance.ref().child('uploads/$fileName');
StorageUploadTask uploadTask = firebaseStorageRef.putFile(fil);
StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
taskSnapshot.ref.getDownloadURL().then(
(value) {
});
}
),
],
cancelButton: CupertinoActionSheetAction(
child: Text("Cancel"),
onPressed: () {
Navigator.pop(context);
},
),
);
showCupertinoModalPopup(context: context, builder: (context) => action);
}
#override
void dispose() {
_currentPageNotifier.dispose();
super.dispose();
}
}
any help would be amazing
thanks in advance!!!

FLUTTER - Can someone help me get this post button to execute?

I hope you all are doing well today. I have another flutter issue that I have been stuck on for the past few days now. I'm attempting to upload this data to my firestore instance, but my post button never seems to be triggering. I have attempted to print a statement from the method that it evokes, but I can't seem to get that to work either. I'm attempting to create a social media app, and any and all help would be appreciated.
My main goal is to get the post button to execute in upload.dart.
I have also included home.dart since the two classes are connected in terms of performance.
upload.dart
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:fluttermedia/models/user.dart';
import 'package:fluttermedia/pages/home.dart';
import 'package:fluttermedia/widgets/progress.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:image/image.dart' as Im;
import 'package:uuid/uuid.dart';
class Upload extends StatefulWidget {
final User currentUser;
Upload({this.currentUser});
#override
_UploadState createState() => _UploadState();
}
class _UploadState extends State<Upload> {
TextEditingController locationController = TextEditingController();
TextEditingController captionController = TextEditingController();
File file;
bool isUploading = false;
String postId = Uuid().v4();
handleChooseFromGallery() async{
Navigator.pop(context);
File file = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
this.file = file;
});
}
handleTakePhoto() async {
Navigator.pop(context);
File file = await ImagePicker.pickImage(source: ImageSource.camera,maxHeight: 675,maxWidth: 960);
setState(() {
this.file = file;
});
}
selectImage(parentContext){
return showDialog(
context: parentContext,
builder: (context) {
return SimpleDialog(
title: Text("Create Post"),
children: <Widget>[
SimpleDialogOption(
child: Text("Photo With Camera"),
onPressed: handleTakePhoto,
),
SimpleDialogOption(
child: Text("Image from Gallery"),
onPressed: handleChooseFromGallery,
),
SimpleDialogOption(
child: Text("Cancel"),
onPressed: () => Navigator.pop(context),
),
],
);
}
);
}
Container buildSplashScreen(){
return Container(
color: Theme.of(context).accentColor.withOpacity(0.6),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SvgPicture.asset('assets/images/upload.svg',height: 260.0,),
Padding(
padding: EdgeInsets.only(top:20.0),
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8.0),
),
child: Text(
"Upload Image",
style: TextStyle(
color: Colors.white,
fontSize: 22.0,
),
),
color: Colors.deepOrange,
onPressed: () => selectImage(context),
),
)
],
),
);
}
clearImage(){
setState(() {
file = null;
});
}
//This compresses images for firebase
compressImage() async{
final tempDir = await getTemporaryDirectory();
final path = tempDir.path;
Im.Image imageFile = Im.decodeImage(file.readAsBytesSync());
final compressedImageFile = File('$path/img_$postId.jpg')..writeAsBytesSync(Im.encodeJpg(imageFile,quality: 85));
setState(() {
file = compressedImageFile;
});
}
Future<String> uploadImage(imageFile) async{
StorageUploadTask uploadTask = storageRef.child("post_$postId.jpg").putFile(imageFile);
StorageTaskSnapshot storageSnap = await uploadTask.onComplete;
String downloadUrl = await storageSnap.ref.getDownloadURL();
return downloadUrl;
}
//upload new info to firestore that creates a new collection
createPostInFirestore({String mediaUrl, String location, String description}){
postsRef.document(widget.currentUser.id)
.collection("userPosts")
.document(postId)
.setData({
"postId": postId,
"ownerId": widget.currentUser.id,
"username": widget.currentUser.username,
"mediaUrl": mediaUrl,
"description": description,
"location": location,
"timestamp": timeStamp,
"likes":{}
});
}
//Getting the info from the caption, location and pic
handleSubmit() async{
setState(() {
isUploading = true;
});
await compressImage();
String mediaUrl = await uploadImage(file);
createPostInFirestore(
mediaUrl: mediaUrl,
location: locationController.text,
description: captionController.text,
);
captionController.clear();
locationController.clear();
setState(() {
file = null;
isUploading = false;
});
}
Scaffold buildUploadForm(){
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white70,
leading: IconButton(
icon: Icon(Icons.arrow_back,color: Colors.black,),
onPressed: clearImage,
),
title: Text(
"Caption Post",
style: TextStyle(color: Colors.black),
),
actions: <Widget>[
FlatButton(
onPressed: () => isUploading ? null : () => handleSubmit(),
child: Text(
"Post",
style: TextStyle(
color: Colors.blueAccent,
fontWeight: FontWeight.bold,
fontSize: 20.0,
),
),
)
],
),
body: ListView(
children: <Widget>[
isUploading ? linearProgress(context):Text(""),
Container(
height: 220.0,
width: MediaQuery.of(context).size.width*0.8,
child: Center(
child: AspectRatio(
aspectRatio: 16/9,
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
image: FileImage(file),
)
),
),
),
),
),
Padding(
padding: EdgeInsets.only(top:10),
),
ListTile(
leading: CircleAvatar(
backgroundImage: CachedNetworkImageProvider(widget.currentUser.photoUrl),
),
title: Container(
width: 250.0,
child: TextField(
controller: captionController,
decoration: InputDecoration(
hintText: "Write a Caption...",
border: InputBorder.none,
),
),
),
),
Divider(),
ListTile(
leading: Icon(Icons.pin_drop,color: Colors.orange,size: 35.0),
title: Container(
width: 250.0,
child: TextField(
controller: locationController,
decoration: InputDecoration(
hintText: "Where was this photo taken",
border: InputBorder.none,
),
),
),
),
Container(
width: 200.0,
height: 100.0,
alignment: Alignment.center,
child: RaisedButton.icon(
label: Text(
"Use Current Location",
style: TextStyle(color: Colors.white),
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0),
),
color: Colors.blue,
onPressed: () => print("Get user location"),
icon: Icon(
Icons.my_location,
color: Colors.white,
),
),
)
],
),
);
}
#override
Widget build(BuildContext context) {
return file == null ? buildSplashScreen() : buildUploadForm();
}
}
home.dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttermedia/models/user.dart';
import 'package:fluttermedia/pages/activity_feed.dart';
import 'package:fluttermedia/pages/create_account.dart';
import 'package:fluttermedia/pages/profile.dart';
import 'package:fluttermedia/pages/search.dart';
import 'package:fluttermedia/pages/upload.dart';
import 'package:google_sign_in/google_sign_in.dart';
final GoogleSignIn googleSignIn = GoogleSignIn();
final StorageReference storageRef = FirebaseStorage.instance.ref();
final usersRef = Firestore.instance.collection('users');
final postsRef = Firestore.instance.collection('posts');
final DateTime timeStamp = DateTime.now();
User currentUser;
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
bool isAuth = false;
PageController pageController;
int pageIndex = 0;
#override
void initState() {
super.initState();
pageController = PageController();
// Detects if user signs in
googleSignIn.onCurrentUserChanged.listen((account) {
handleSignIn(account);
}, onError: (err){
print('Error sigining in: $err');
});
//Reauthenticate user when app is opened
googleSignIn.signInSilently(suppressErrors: false)
.then((account) =>
handleSignIn(account)).catchError((err){
print('Error signing in on retry: $err');
});
}
#override
Widget build(BuildContext context) {
return isAuth ? buildAuthScreen() : buildUnAuthScreen();
}
#override
void dispose(){
pageController.dispose();
super.dispose();
}
//Helper Functions
//The sign in section of the code
handleSignIn(GoogleSignInAccount account){
if(account != null){
createUserInFirestore();
setState(() {
isAuth = true;
});
}else{
setState(() {
isAuth = false;
});
}
}
login(){
googleSignIn.signIn();
}
logout(){
googleSignIn.signOut();
}
onPageChanged(int pageIndex){
setState(() {
this.pageIndex = pageIndex;
});
}
createUserInFirestore() async{
// 1) Check if user exists in users collection in database (According to id)
final GoogleSignInAccount user = googleSignIn.currentUser;
DocumentSnapshot doc = await usersRef.document(user.id).get();
if(!doc.exists){
// 2) If the user doesn't exist, take them to create account page
final username = await Navigator.push(context, MaterialPageRoute(builder: (context) => CreateAccount()));
// 3) get username from create account, use it to make new user document in users collection
usersRef.document(user.id).setData({
"id":user.id,
"username":username,
"photoUrl": user.photoUrl,
"email":user.email,
"displayName": user.displayName,
"bio":"",
"timeStamp": timeStamp,
});
doc = await usersRef.document(user.id).get();
}
currentUser = User.fromDocument(doc);
//print(currentUser);
//print(currentUser.username);
}
onTap(int pageIndex){
//This what you would use to animate in between the different screens
pageController.animateToPage(
pageIndex,
duration: Duration(milliseconds: 300),
curve: Curves.easeInOut
);
}
//UI Code
Widget buildAuthScreen() {
return Scaffold(
body: PageView(
children: <Widget>[
//Timeline(),
RaisedButton(
child: Text('Logout'),
onPressed: logout,
),
ActivityFeed(),
Upload(currentUser: currentUser),
Search(),
Profile(),
],
controller: pageController,
onPageChanged: onPageChanged,
physics: NeverScrollableScrollPhysics(),
),
bottomNavigationBar: CupertinoTabBar(
currentIndex: pageIndex,
onTap: onTap,
activeColor: Theme.of(context).primaryColor,
items: [
BottomNavigationBarItem(icon: Icon(Icons.whatshot),),
BottomNavigationBarItem(icon: Icon(Icons.notifications_active),),
BottomNavigationBarItem(icon: Icon(Icons.photo_camera, size: 34.0,),),
BottomNavigationBarItem(icon: Icon(Icons.search),),
BottomNavigationBarItem(icon: Icon(Icons.account_circle),),
],
),
);
/*return RaisedButton(
child: Text('Logout'),
onPressed: logout,
);*/
}
Scaffold buildUnAuthScreen() {
return Scaffold(
body: Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topRight,
end: Alignment.bottomLeft,
colors: [
Theme.of(context).primaryColor,
Theme.of(context).accentColor,
]
)
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text('FlutterMedia',
style: TextStyle(
fontFamily: "Signatra",
fontSize: 90.0,
color: Colors.white
),
),
GestureDetector(
onTap:() => login(),
child: Container(
width: 260,
height: 60,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/google_signin_button.png'),
fit: BoxFit.cover,
),
),
),
)
],
),
),
);
}
}
onPressed: () => isUploading ? null : () => handleSubmit(),
Well, there's your problem. You meant to have a tertiary condition that makes onPressed call handleSubmit when isUploading is false. Instead, you have made onPressed into a function that returns a function.
To hopefully make that more clear, let's blow this function up into proper non-lambda functions and if/else blocks:
onPressed: () {
if (isUploading) {
return null;
} else {
return () {
handleUpload();
}
}
}
So consider what happens when the button is pressed. It calls the outer function, which checks isUploading. If true, the function returns null, and if false, it returns another function that, if called, calls handleUpload. So how this plays out is that onPressed will never be null (it just returns null sometimes) and handleUpload never gets called (since the inner function that is returned is never then called itself).
Remove the outer lambda and it will work:
onPressed: isUploading ? null : () => handleSubmit(),

MyAppState is not displaying anything

import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:image_picker/image_picker.dart';
import 'package:qrscan/qrscan.dart' as scanner;
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Uint8List bytes = Uint8List(0);
TextEditingController _inputController;
TextEditingController _outputController;
#override
initState() {
super.initState();
this._inputController = new TextEditingController();
this._outputController = new TextEditingController();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Colors.grey[300],
body: Builder(
builder: (BuildContext context) {
return ListView(
children: <Widget>[
_qrCodeWidget(this.bytes, context),
Container(
color: Colors.white,
child: Column(
children: <Widget>[
TextField(
controller: this._inputController,
keyboardType: TextInputType.url,
textInputAction: TextInputAction.go,
onSubmitted: (value) => _generateBarCode(value),
decoration: InputDecoration(
prefixIcon: Icon(Icons.text_fields),
helperText: 'Please input your code to generage qrcode image.',
hintText: 'Please Input Your Code',
hintStyle: TextStyle(fontSize: 15),
contentPadding: EdgeInsets.symmetric(
horizontal: 7, vertical: 15),
),
),
SizedBox(height: 20),
TextField(
controller: this._outputController,
maxLines: 2,
decoration: InputDecoration(
prefixIcon: Icon(Icons.wrap_text),
helperText: 'The barcode or qrcode you scan will be displayed in this area.',
hintText: 'The barcode or qrcode you scan will be displayed in this area.',
hintStyle: TextStyle(fontSize: 15),
contentPadding: EdgeInsets.symmetric(
horizontal: 7, vertical: 15),
),
),
SizedBox(height: 20),
this._buttonGroup(),
SizedBox(height: 70),
],
),
),
],
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: () => _scanBytes(),
tooltip: 'Take a Photo',
child: const Icon(Icons.camera_alt),
),
),
);
}
Widget _qrCodeWidget(Uint8List bytes, BuildContext context) {
return Padding(
padding: EdgeInsets.all(20),
child: Card(
elevation: 6,
child: Column(
children: <Widget>[
Container(
child: Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Icon(Icons.verified_user, size: 18, color: Colors.green),
Text(' Generate Qrcode', style: TextStyle(fontSize: 15)),
Spacer(),
Icon(Icons.more_vert, size: 18, color: Colors.black54),
],
),
padding: EdgeInsets.symmetric(horizontal: 10, vertical: 9),
decoration: BoxDecoration(
color: Colors.black12,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(4), topRight: Radius.circular(4)),
),
),
Padding(
padding: EdgeInsets.only(
left: 40, right: 40, top: 30, bottom: 10),
child: Column(
children: <Widget>[
SizedBox(
height: 190,
child: bytes.isEmpty
? Center(
child: Text('Empty code ... ',
style: TextStyle(color: Colors.black38)),
)
: Image.memory(bytes),
),
Padding(
padding: EdgeInsets.only(top: 7, left: 25, right: 25),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Expanded(
flex: 5,
child: GestureDetector(
child: Text(
'remove',
style: TextStyle(
fontSize: 15, color: Colors.blue),
textAlign: TextAlign.left,
),
onTap: () =>
this.setState(() => this.bytes = Uint8List(0)),
),
),
Text('|', style: TextStyle(fontSize: 15, color: Colors
.black26)),
Expanded(
flex: 5,
child: GestureDetector(
onTap: () async {
final success = await ImageGallerySaver.saveImage(
this.bytes);
SnackBar snackBar;
if (success) {
snackBar = new SnackBar(content: new Text(
'Successful Preservation!'));
Scaffold.of(context).showSnackBar(snackBar);
} else {
snackBar =
new SnackBar(content: new Text('Save failed!'));
}
},
child: Text(
'save',
style: TextStyle(
fontSize: 15, color: Colors.blue),
textAlign: TextAlign.right,
),
),
),
],
),
)
],
),
),
Divider(height: 2, color: Colors.black26),
],
),
),
);
}
Widget _buttonGroup() {
return Row(
children: <Widget>[
Expanded(
flex: 1,
child: SizedBox(
height: 120,
child: InkWell(
onTap: () => _generateBarCode(this._inputController.text),
child: Card(
child: Column(
children: <Widget>[
Expanded(
flex: 2,
child: Image.asset('images/generate_qrcode.png'),
),
Divider(height: 20),
Expanded(flex: 1, child: Text("Generate")),
],
),
),
),
),
),
Expanded(
flex: 1,
child: SizedBox(
height: 120,
child: InkWell(
onTap: _scan,
child: Card(
child: Column(
children: <Widget>[
Expanded(
flex: 2,
child: Image.asset('images/scanner.png'),
),
Divider(height: 20),
Expanded(flex: 1, child: Text("Scan")),
],
),
),
),
),
),
Expanded(
flex: 1,
child: SizedBox(
height: 120,
child: InkWell(
onTap: _scanPhoto,
child: Card(
child: Column(
children: <Widget>[
Expanded(
flex: 2,
child: Image.asset('images/albums.png'),
),
Divider(height: 20),
Expanded(flex: 1, child: Text("Scan Photo")),
],
),
),
),
),
),
],
);
}
Future _scan() async {
String barcode = await scanner.scan();
if (barcode == null) {
print('nothing return.');
} else {
this._outputController.text = barcode;
}
}
Future _scanPhoto() async {
String barcode = await scanner.scanPhoto();
this._outputController.text = barcode;
}
Future _scanPath(String path) async {
String barcode = await scanner.scanPath(path);
this._outputController.text = barcode;
}
Future _scanBytes() async {
File file = await ImagePicker.pickImage(source: ImageSource.camera);
Uint8List bytes = file.readAsBytesSync();
String barcode = await scanner.scanBytes(bytes);
this._outputController.text = barcode;
}
Future _generateBarCode(String inputCode) async {
Uint8List result = await scanner.generateBarCode(inputCode);
this.setState(() => this.bytes = result);
}
}
class MyAppState extends State<MyApp> {
Future<SharedPreferences> _sPrefs = SharedPreferences.getInstance();
final TextEditingController controller = TextEditingController();
List<String> listOne, listTwo;
#override
void initState() {
super.initState();
listOne = [];
listTwo = [];
}
Future<Null> addString() async {
final SharedPreferences prefs = await _sPrefs;
listOne.add(controller.text);
prefs.setStringList('list', listOne);
setState(() {
controller.text = '';
});
}
Future<Null> clearItems() async {
final SharedPreferences prefs = await _sPrefs;
prefs.clear();
setState(() {
listOne = [];
listTwo = [];
});
}
Future<Null> getStrings() async {
final SharedPreferences prefs = await _sPrefs;
listTwo = prefs.getStringList('list');
setState(() {});
}
Future<Null> updateStrings(String str) async {
final SharedPreferences prefs = await _sPrefs;
setState(() {
listOne.remove(str);
listTwo.remove(str);
});
prefs.setStringList('list', listOne);
}
#override
Widget build(BuildContext context) {
getStrings();
return Center(
child: ListView(
children: <Widget>[
TextField(
controller: controller,
decoration: InputDecoration(
hintText: 'Type in something...',
)),
RaisedButton(
child: Text("Submit"),
onPressed: () {
addString();
},
),
RaisedButton(
child: Text("Clear"),
onPressed: () {
clearItems();
},
),
Flex(
direction: Axis.vertical,
children: listTwo == null
? []
: listTwo
.map((String s) => Dismissible(
key: Key(s),
onDismissed: (direction) {
updateStrings(s);
},
child: ListTile(
title: Text(s),
)))
.toList(),
)
],
),
);
}
}
Here the first Appstate creates a Qr code reader. Second is for creating an input controller with shared preferences that can store and retrieve data locally. But when running the code the app displays only the qrscan part and 2nd is not working. I'm new to Flutter. I've just started working on Android Studio. Can anybody help please?
Try to call Another class from home property of the MyApp class.
As you can see in this image
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
//Here I have called MyWidget Class
home: MyWidget()
);
}
}
class MyWidget extends StatefulWidget {
#override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
Uint8List bytes = Uint8List(0);
TextEditingController _inputController;
TextEditingController _outputController;
#override
initState() {
super.initState();
this._inputController = new TextEditingController();
this._outputController = new TextEditingController();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(

Categories

Resources