I've been building a demo app to practice flutter, the app's running perfectly fine in the emulator as well as on real devices when connected. But now, I've been trying to run the APK file on my mobile and it seems to not work. I can log in to the app meaning the internet permission is working. But when it comes to the home screen which pulls data from a server, the app does not work. Maybe there's something wrong in the code relevant, but I can't seem to fix it.
I've attached the code for the home screen as well, the provider part is the thing that is having issues. AND ALSO THE DATABASE HAS THE DATA MEANING THE LIST IS NOT EMPTY AT ALL
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import './new_enquiry_screen.dart';
import '../providers/enquiries_provider.dart';
import '../screens/new_enquiry_screen.dart';
import '../widgets/drawer_widget.dart';
import '../widgets/follow_up_list_tile_widget.dart';
class EnquiryScreen extends StatelessWidget {
const EnquiryScreen({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
child: Scaffold(
drawer: DrawerWidget(),
appBar: AppBar(
bottom: const TabBar(
tabs: [
Tab(text: 'Follow Ups'),
Tab(text: 'Leads'),
Tab(text: 'Past'),
],
),
title: Text(
'Enquiries',
),
backgroundColor: Theme.of(context).primaryColor,
),
body: TabBarView(
children: [
ChangeNotifierProvider<EnquiriesProvider>.value(
value: EnquiriesProvider(),
child: Consumer<EnquiriesProvider>(
builder: (_, provider, child) {
int length = provider.enquiries.length;
return length == 0
? Center(
child: CircularProgressIndicator(),
)
: ListView.builder(
itemCount: length,
itemBuilder: (_, index) {
return FollowUpListTileWidget(
provider.enquiries.elementAt(index),
);
},
);
},
),
),
const Center(
child: Text('Leads Up'),
),
const Center(
child: Text('Past Up'),
),
],
),
floatingActionButton: FloatingActionButton(
backgroundColor: Theme.of(context).primaryColor,
onPressed: () {
Navigator.of(context).pushNamed(NewEnquiryScreen.routeName);
},
child: Icon(
Icons.add,
color: Theme.of(context).accentColor,
size: 30,
),
),
),
);
}
}
import 'package:flutter/material.dart';
import '../models/enquiry.dart';
class FollowUpListTileWidget extends StatelessWidget {
const FollowUpListTileWidget(this._enquiry, {Key? key}) : super(key: key);
final Enquiry _enquiry;
#override
Widget build(BuildContext context) {
return Card(
elevation: 10,
margin: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 5.0),
child: ListTile(
leading: CircleAvatar(
child: Text(
_enquiry.name.characters.first.toUpperCase(),
style: TextStyle(
color: Theme.of(context).accentColor,
),
),
backgroundColor: Theme.of(context).primaryColor,
),
title: Text(_enquiry.name),
subtitle: FittedBox(child: Text(_enquiry.email)),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
color: Theme.of(context).primaryColor,
onPressed: () {},
icon: const Icon(
Icons.phone,
),
),
IconButton(
color: Theme.of(context).primaryColor,
onPressed: () {},
icon: const Icon(Icons.whatsapp),
),
IconButton(
color: Theme.of(context).primaryColor,
onPressed: () {},
icon: const Icon(Icons.edit),
),
],
),
),
);
}
}
try to run app in debug mode in real device, if it is working then check in manifest file you have given internet permission or not inside android/app/main/AndroidManifest.xml by default in debug mode internet permission is already exits and most important please remove all caps from your question title as it is very difficult to read.
Related
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
class ProfilePage extends StatefulWidget {
const ProfilePage({Key? key}) : super(key: key);
#override
State<ProfilePage> createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
File ?imageFile;
TextEditingController fullnamecontroller=TextEditingController();
void selectImage(ImageSource source)async {
XFile?pickedFile= await ImagePicker().pickImage(source: source);
if(pickedFile!=null){
cropImage(pickedFile);
}
}
void cropImage(XFile file)async{
CroppedFile?croppedImage= await ImageCropper().cropImage(sourcePath: file.path,aspectRatio: CropAspectRatio(ratioX: 1, ratioY: 1),compressQuality: 20
);
if (croppedImage!=null){
setState((){
imageFile=croppedImage as File?;
});
}
}
void ShowphotoOption(){
showDialog(context: context, builder: (context){return AlertDialog(
title: Text('Select Image'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
onTap: (){selectImage(ImageSource.gallery);
Navigator.pop(context);},
leading: Icon(Icons.photo_album),
title: Text('Selct from gallery'),
),
ListTile(
onTap: (){selectImage(ImageSource.camera);
Navigator.pop(context);},
leading: Icon(Icons.camera_alt),
title: Text('Take photo from camera'),
)
],),
);});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title:Text('Complete Your Profile')
),
body: SafeArea(
child: Container(
child: Padding(
padding: const EdgeInsets.all(20),
child: ListView(
children: [
CupertinoButton(
padding: EdgeInsets.all(0),
onPressed: (){
ShowphotoOption();
},
child: CircleAvatar(
backgroundImage: FileImage(imageFile!),
child: Icon(Icons.person,size: 60,),
radius: 60,
),
),
SizedBox(height: 10,),
TextField(
decoration: InputDecoration(
labelText: 'Full name',
),
),
SizedBox(height: 20,),
CupertinoButton(
onPressed: (){},
color: Colors.lightBlue,
child: Text('Submit'),
)
],
),
),
),
),
);
}
}
I made a simple app with image picker and image cropper pakage and when writing this code i got this error.
Whenever I try to run this code, it shows on my device "Null check operator used on a null value.." Although I set the state. Can you please solve this error? I am new to flutter, I dont know why it shows this error..
Instead of that backgroundImage: FileImage(imageFile!),
Use this backgroundImage: imageFile != null ? FileImage(imageFile!) : null,
Because you're trying to print the screen without putting a picture in the imageFile
This is my homepage.dart. The error here said that there is an unexpected null value. I've been trying to debug this for the day but i still could not manage to find it, how to solve this problem? When i try to run the code. It won't shows the data from the 'Parking' which is inside the firestore database. The data was indeed there but it wont show inside this page. Can anyone help me with this ?
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'addparking.dart';
class AdminHomePage extends StatefulWidget {
const AdminHomePage({Key? key}) : super(key: key);
#override
State<AdminHomePage> createState() => _AdminHomePageState();
}
class _AdminHomePageState extends State<AdminHomePage> {
CollectionReference ref = FirebaseFirestore.instance.collection('Parking');
//DELETE
Future<void> _deleteProduct(String productId) async {
await ref.doc(productId).delete();
// Show a snackbar
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('You have successfully deleted a product')));
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.lightBlueAccent,
appBar: AppBar(
backgroundColor: Color(0xFF121212),
elevation: 0.0,
title: const Text('Admin Page',
style:TextStyle(
color: Color(0xFFFFFFFF),
fontWeight: FontWeight.bold,
),
),
centerTitle:true,
),
body: StreamBuilder(
stream: FirebaseFirestore.instance.collection('Parking').snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
if(snapshot.hasData){
return ListView.builder(
itemCount: snapshot.data!.docs.length,
itemBuilder: (context,index){
final DocumentSnapshot documentSnapshot = (snapshot.data!.docs[index]);
return Card(
margin: const EdgeInsets.all(10),
child: ListTile(
title: Text(documentSnapshot['level']),
subtitle: Text(documentSnapshot['parking']),
trailing: Row(
children: [
IconButton(
icon: const Icon(Icons.edit),
onPressed: (){}
),
IconButton(
icon: const Icon(Icons.delete),
onPressed: () => _deleteProduct(documentSnapshot.id),
),
],
),
),
);
});
}
return const Center(
child: CircularProgressIndicator(),
);
},
),
drawer: const NavigationDrawer(),
);
}
}
class NavigationDrawer extends StatelessWidget {
const NavigationDrawer({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) => Drawer(
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget> [
buildHeader(context),
buildMenuItems(context),
],
),
),
);
Widget buildHeader (BuildContext context) => Container(
color: Colors.amber,
child: InkWell(
onTap: (){},
child: Container(
padding: EdgeInsets.only(
top: 24 + MediaQuery.of(context).padding.top,
bottom: 24,
),
child: Column(
children: const [
CircleAvatar(
radius: 40,
backgroundImage: NetworkImage(
'https://www.shutterstock.com/image-vector/people-icon-vector-illustration-flat-design-405042562'
),
),
SizedBox(height: 12),
Text(
'Admin'
)
],
),
),
),
);
Widget buildMenuItems (BuildContext context) => Container(
padding: const EdgeInsets.all(24),
child: Wrap(
children: [
ListTile(
leading: const Icon(Icons.home_outlined),
title: const Text('Home'),
onTap:(){}
),
const Divider(color: Colors.black54,),
ListTile(
leading: const Icon(Icons.home_outlined),
title: const Text('Add Parking'),
onTap:(){
Navigator.pop(context);
Navigator.of(context).push(MaterialPageRoute(builder: (context) => AddParking(),));
}
),
const Divider(color: Colors.black54,),
ListTile(
leading: const Icon(Icons.home_outlined),
title: const Text('Delete Parking'),
onTap:(){}
),
const Divider(color: Colors.black54,),
ListTile(
leading: const Icon(Icons.home_outlined),
title: const Text('Update Parking'),
onTap:(){}
),
const Divider(color: Colors.black54,),
ListTile(
leading: const Icon(Icons.home_outlined),
title: const Text('Report Feedback'),
onTap:(){}
),
const Divider(color: Colors.black54,),
ListTile(
leading: const Icon(Icons.home_outlined),
title: const Text('Payment Setup'),
onTap:(){}
),
],
),
);
}
try
1- documentSnapshot?['level']
2- documentSnapshot?['parking']
It's really hard to track down the error without the stacktrace but you can try to change the following lines:
Text(documentSnapshot['level'] ?? "")
Text(documentSnapshot['parking'] ?? "")
Text() requires a string as a parameter that isn't null and documentSnapshot['level'] returns an nullable value because the key level might not exist. Same for parking.
i obseved that the app is crashing after i add that listview builder if we dont add that app running smoothly
i am still a new bee so i dont know much i just started
if u want u can see whole app code in
https://github.com/Pradeep7976/E_com_app/tree/master/shop_app
this is a garbage i am writing this cause stack overflow is suggesting to add more description it is saying the post is mostly code add some more description
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/cart.dart' show Cart;
import '../widgets/cart_item.dart';
import '../providers/orders.dart';
class CartScreen extends StatelessWidget {
static const routeName = '/cart';
#override
Widget build(BuildContext context) {
final cart = Provider.of<Cart>(context);
return Scaffold(
appBar: AppBar(
title: Text('Your Cart'),
),
body: Column(
children: <Widget>[
Card(
margin: EdgeInsets.all(5),
child: Padding(
padding: EdgeInsets.all(15),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
'Total',
style: TextStyle(fontSize: 20),
),
Spacer(),
Chip(
label: Text(
'₹${cart.totalAmount.toStringAsFixed(2)}',
style: TextStyle(color: Colors.yellow),
),
backgroundColor: Theme.of(context).primaryColor,
),
FlatButton(
child: Text('ORDER NOW'),
onPressed: () {
Provider.of<Orders>(context, listen: false).addOrder(
cart.items.values.toList(),
cart.totalAmount,
);
cart.clear();
},
textColor: Theme.of(context).primaryColor,
),
],
),
),
),
SizedBox(height: 10),
Expanded(
child: ListView.builder(
itemBuilder: (ctx, i) => CartItem(
cart.items.values.toList()[i].id,
cart.items.keys.toList()[i],
cart.items.values.toList()[i].price,
cart.items.values.toList()[i].quantity,
cart.items.values.toList()[i].title,
),
itemCount: cart.items.length,
),
)
],
),
);
}
}
this happens when there is an infinite loop in your app
perhaps your problem is the number of cart items which tries to build so many widgets
I'm building my quiz app and my quizpage is taking solid shape but here's a problem i have. I added a Willpopscope just so that my users can't go back to the beginning when the quiz has started and it brings up a dialog box. Here's the code:
import 'dart:convert';
//import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class GetJson extends StatelessWidget {
const GetJson({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: DefaultAssetBundle.of(context).loadString("assets/python.json"),
builder: (context, snapshot) {
var mydata = jsonDecode(snapshot.data.toString());
if (mydata == null) {
return Scaffold(
body: Center(
child: Text(
"Loading",
),
),
);
} else {
return QuizPage();
}
},
);
}
}
class QuizPage extends StatefulWidget {
QuizPage({Key? key}) : super(key: key);
#override
_QuizPageState createState() => _QuizPageState();
}
class _QuizPageState extends State<QuizPage> {
Widget choicebutton() {
return Padding(
padding: EdgeInsets.symmetric(
vertical: 10.0,
horizontal: 20.0,
),
child: MaterialButton(
onPressed: () {},
child: Text(
"option 1",
style: TextStyle(
color: Colors.white,
fontFamily: "Alike",
fontSize: 16.0,
),
maxLines: 1,
),
color: Colors.indigo,
splashColor: Colors.indigo[700],
highlightColor: Colors.indigo[700],
minWidth: 200.0,
height: 45.0,
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)),
),
);
}
#override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitDown, DeviceOrientation.portraitUp]);
return WillPopScope(
onWillPop: () {
return showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text(
"Quizstar",
),
content: Text("You Can't Go Back At This Stage"),
actions: [
// ignore: deprecated_member_use
FlatButton(onPressed: () {
Navigator.of(context).pop();
},
child: Text(
"Ok",
),
)
],
)
);
},
child: Scaffold(
body: Column(
children: [
Expanded(
flex: 3,
child: Container(
padding: EdgeInsets.all(15.0),
alignment: Alignment.bottomLeft,
child: Text(
"This is a sample question which will be displayed?",
style: TextStyle(
fontSize: 16.0,
fontFamily: "Quando",
),
),
),
),
Expanded(
flex: 6,
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
choicebutton(),
choicebutton(),
choicebutton(),
choicebutton(),
],
),
),
),
Expanded(
flex: 1,
child: Container(
alignment: Alignment.topCenter,
child: Center(
child: Text(
"30",
style: TextStyle(
fontSize: 35.0,
fontWeight: FontWeight.w700,
fontFamily: "Times New Roman",
),
),
),
),
),
],
),
),
);
}
}
The error is in the showDialog() but i can't seem to figure it out.
Thanks a lot guys.
This might help
On your willpop scope function do this instead
onWillPop: () {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text(
"Quizstar",
),
content: Text("You Can't Go Back At This Stage"),
actions: [
// ignore: deprecated_member_use
FlatButton(onPressed: () {
Navigator.of(context).pop();
},
child: Text(
"Ok",
),
)
],
)
);
return true;
),
child : your widget
Okay i figured it out
return WillPopScope(
onWillPop: () async {
print("Back Button Pressed");
final shouldPop = await showWarning(context);
return shouldPop ?? false;
},
Then i went ahead to define showWarning like this, then defined my dialog box inside it:
Future<bool?> showWarning(BuildContext context) async => showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: Text("Quizstar"),
content: Text("You cannot go back at this stage"),
actions: [
ElevatedButton(
onPressed: () => Navigator.pop(context, false),
child: Text("Okay"),
),
//ElevatedButton(
// onPressed: () => Navigator.pop(context, true),
// child: Text("Yes"),
//),
],
),
);
Tips: Don't forget to make the future a bool by writing inside it with it's '?'
I am developing an application for shopping using flutter, so I am stacking somewhere and I need help.
I use image_picker code provided on pub.dev (https://pub.dev/packages/image_picker#-readme-tab-) then I developed a page for adding products on my app, so when I click on the camera icon or gallery icon to pick image the app crashes and opens the camera screen/gallery screen.
my big problem is; it works fine with the emulator but on a real phone, it crushes.
I tried to use retrieveLostData() as shown on pub.dev, but I didn't know where to use it.
Bellow is my code
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:flutter/widgets.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:firebase_storage/firebase_storage.dart';
//my imports
import 'package:myshop/main.dart';
class ImageCapture extends StatefulWidget {
#override
_ImageCaptureState createState() => _ImageCaptureState();
}
class _ImageCaptureState extends State<ImageCapture> {
File _imageFile;
Future<void> _cropImage() async {
File cropped = await ImageCropper.cropImage(
sourcePath: _imageFile.path,);
setState(() {
_imageFile = cropped ?? _imageFile;
});
}
// pick image from galery or camera
Future<void> _pickImage(ImageSource source) async {
File selected = await ImagePicker.pickImage(source: source);
setState(() {
_imageFile = selected;
});
}
//remove image
void _clear() {
setState(() => _imageFile = null);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0.0,
backgroundColor: Colors.orange[700],
title: Text(
'Image Capture',
style: TextStyle(fontFamily: 'Exo', fontSize: 13.0),
),
actions: <Widget>[
IconButton(
icon: Icon(
Icons.search,
color: Colors.white,
size: 23.0,
),
onPressed: () {},
),
IconButton(
icon: Icon(
Icons.home,
size: 18,
color: Colors.white,
),
onPressed: () => Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => Home())))
],
),
//pick image from camera or gallery
bottomNavigationBar: BottomAppBar(
color: Colors.cyan[900],
child: Container( margin: EdgeInsets.fromLTRB(30, 0, 30, 0),
child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
IconButton(
icon: Icon(Icons.photo_camera, color: Colors.orange, size: 18,),
onPressed: () => _pickImage(ImageSource.camera),
),
IconButton(
icon: Icon(Icons.photo_library, color: Colors.orange, size: 18,),
onPressed: () => _pickImage(ImageSource.gallery),
),
],
),
),
),
body: ListView(
children: <Widget>[
if (_imageFile != null) ...[
Image.file(_imageFile),
Row( mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
FlatButton(
child: Icon(Icons.crop, size: 18,),
onPressed: _cropImage,
),
FlatButton(
child: Icon(Icons.refresh,size: 18,),
onPressed: _clear,
),
],
),
], if (_imageFile==null)...[
Center(
child: Text('No Image Captured', style: TextStyle(color: Colors.black54),),
)
]
],
),
);
}
}
You need to add the camera and storage permission in the AndroidManifest.xml file of your project.
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
also, you need to check for runtime permission for both in your activity.
Head to Storage permission error in Marshmallow for more information.