Why is my Flutter PageView resetting when new any permission is selected by a user (iOS) - flutter

My app asks permission to access the photo library, camera, microphone, and location on the CreatePostScreen(). Whenever a user selects any option for those permission prompts, the PageView resets and goes to the first tab for some reason. None of the code in create_post_screen.dart calls for this and it only happens after permissions are set. I cannot figure out why this is happening.
create_post_screen.dart:
class CreatePostScreen extends StatefulWidget {
const CreatePostScreen({Key? key}) : super(key: key);
#override
State<CreatePostScreen> createState() => _CreatePostScreenState();
}
class _CreatePostScreenState extends State<CreatePostScreen> {
final _locationNameFormKey = GlobalKey<FormState>();
final _locationNameController = TextEditingController();
bool _isLoading = false;
List<String> originalFiles = [];
List<File> imageFiles = [];
void selectImages() async {
final result = await showModalActionSheet(
context: context,
title: 'Select Image Source',
actions: [
const SheetAction(label: 'Existing Images', key: 'existing'),
const SheetAction(label: 'New Image', key: 'new')
]);
if (result == 'new' && imageFiles.length < 4) {
newImage();
} else if (result == 'existing' && imageFiles.length < 4) {
existingImages();
}
}
void newImage() async {
setState(() {
_isLoading = true;
});
final XFile? image =
await ImagePicker().pickImage(source: ImageSource.camera);
if (image == null) return;
cropImages([image.path]);
}
void existingImages() async {
setState(() {
_isLoading = true;
});
final List<XFile>? selectedImages = await ImagePicker().pickMultiImage();
if (selectedImages == null) return;
int ableToAdd = 4 - imageFiles.length;
if (selectedImages.length > ableToAdd) {
List<XFile>? filesToAdd = selectedImages.sublist(0, ableToAdd);
List<String> imagePaths = [];
for (var selectedImage in filesToAdd) {
imagePaths.add(selectedImage.path);
}
cropImages(imagePaths);
} else {
List<String> imagePaths = [];
for (var selectedImage in selectedImages) {
imagePaths.add(selectedImage.path);
}
cropImages(imagePaths);
}
}
void cropImages(List<String> paths) async {
for (var path in paths) {
originalFiles.add(path);
final ImageProperties properties =
await FlutterNativeImage.getImageProperties(path);
final int width = properties.width!;
final int height = properties.height!;
int imageSize = width < height ? width : height;
int x = 0;
int y = 0;
File imageFile =
await FlutterNativeImage.cropImage(path, x, y, imageSize, imageSize);
setState(() {
int index = originalFiles.indexOf(path);
imageFiles.insert(index, imageFile);
_isLoading = false;
});
}
}
void customCrop(int index) async {
final fileToCrop = originalFiles[index];
final croppedFile = await ImageCropper().cropImage(
sourcePath: fileToCrop,
aspectRatio: const CropAspectRatio(ratioX: 1, ratioY: 1),
aspectRatioPresets: [
CropAspectRatioPreset.square
],
uiSettings: [
AndroidUiSettings(toolbarTitle: 'Crop Image'),
IOSUiSettings(title: "Crop Image", showCancelConfirmationDialog: true)
]);
setState(() {
imageFiles[index] = File(croppedFile!.path);
});
}
Position? position;
void _determinePosition() async {
LocationPermission permission;
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
}
Position positionResult = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.lowest);
setState(() {
position = positionResult;
});
}
pkg.User user = Supabase.auth.currentUser!;
final postId = DateTime.now().millisecondsSinceEpoch.toString();
void uploadPost() async {
if (_locationNameFormKey.currentState!.validate()) {
_locationNameFormKey.currentState!.save();
setState(() {
_isLoading = true;
});
String name = _locationNameController.text;
Location location = Location(
position!.latitude,
position!.longitude,
name,
);
List<String> uploadedUrls = [];
for (var file in imageFiles) {
String fileName = '${DateTime.now().millisecondsSinceEpoch}_post.png';
Supabase.storage
.from('posts')
.upload('${user.id}/$fileName', supaFile.File(file.path));
String url = Supabase.storage.from('posts').getPublicUrl('${user.id}/$fileName');
setState(() {
uploadedUrls.add(url);
});
if (imageFiles.length == uploadedUrls.length) {
Post post = Post(
postId,
uploadedUrls,
user.id,
// profile,
location,
DateTime.now().millisecondsSinceEpoch,
);
print(post);
try {
Supabase.db
.from('posts')
.insert(post.toJson())
.then((value) {
setState(() {
imageFiles = [];
originalFiles = [];
_locationNameController.clear();
position = null;
_isLoading = false;
});
});
} catch (error) {
setState(() {
_isLoading = false;
});
print(error);
}
}
}
}
}
Widget imageItem(int index) {
File imageFile = imageFiles[index];
return SizedBox(
height: 200,
width: 200,
child: Card(
clipBehavior: Clip.hardEdge,
child: Stack(
children: [
Image.file(imageFile, fit: BoxFit.fill),
Align(
alignment: Alignment.bottomRight,
child: Padding(
padding: const EdgeInsets.all(5),
child: Row(
children: [
SizedBox(
height: 35,
width: 35,
child: FittedBox(
child: FloatingActionButton(
onPressed: () {
setState(() {
customCrop(index);
});
},
child: const Icon(Icons.edit_outlined),
),
),
),
const SizedBox(width: 5),
SizedBox(
height: 35,
width: 35,
child: FittedBox(
child: FloatingActionButton(
onPressed: () {
setState(() {
imageFiles.removeAt(index);
originalFiles.removeAt(index);
});
},
child: const Icon(Icons.delete_forever_sharp),
),
),
),
],
),
),
)
],
),
),
);
}
Widget picker() {
return imageFiles.isEmpty
? GestureDetector(
onTap: () {
selectImages();
},
child: Center(
child: Container(
decoration: BoxDecoration(
color: const Color(0xFFd3d8e9),
borderRadius: BorderRadius.circular(10),
),
height: 150,
width: 300,
child: const Center(
child: Text(
'Press to add Images - Required',
style: TextStyle(color: Colors.red),
),
),
),
),
)
: Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
decoration: BoxDecoration(
color: const Color(0xFFd3d8e9),
borderRadius: BorderRadius.circular(10),
),
child: DragAndDropGridView(
physics: const ScrollPhysics(),
itemCount: imageFiles.length,
gridDelegate:
const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 200,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
),
itemBuilder: (context, index) {
return imageItem(index);
},
onWillAccept: () {
return true;
},
onReorder: (oldIndex, newIndex) {
final temp = imageFiles[newIndex];
imageFiles[newIndex] = imageFiles[oldIndex];
imageFiles[oldIndex] = temp;
setState(() {});
},
),
),
),
],
);
}
#override
Widget build(BuildContext context) {
return Stack(
children: [
Scaffold(
resizeToAvoidBottomInset: true,
appBar: FloatingAppBar(
leading: const SizedBox(),
title: const Text('Create Post',
style: TextStyle(color: Color(0xFF7157A0), fontSize: 20)),
actions: [
if (imageFiles.isEmpty || position == null)
const Icon(Icons.send_outlined, color: Colors.grey),
if (imageFiles.isNotEmpty && position != null)
IconButton(
onPressed: () {
uploadPost();
},
icon:
const Icon(Icons.send_outlined, color: Color(0xFF7157A0)),
),
],
),
body: SingleChildScrollView(
child: Column(
children: [
picker(),
Padding(
padding: const EdgeInsets.all(20),
child: Form(
key: _locationNameFormKey,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 80,
width: MediaQuery.of(context).size.width - 40,
child: TextFormField(
controller: _locationNameController,
textInputAction: TextInputAction.done,
keyboardType: TextInputType.name,
decoration: const InputDecoration(
suffix: Icon(Icons.edit_location_outlined,
color: Color(0xFF6C74B4)),
labelText: "Location Name",
floatingLabelStyle:
TextStyle(color: Color(0xFF697CB4)),
enabledBorder: OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(8)),
borderSide: BorderSide(
color: Color(0xFF6B6FAB), width: 1)),
focusedBorder: OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(8)),
borderSide: BorderSide(
color: Color(0xFF697CB4), width: 1)),
),
validator: (name) {
if (name == null) {
return 'This cannot be left empty';
}
if (name.length < 4 || name.length > 15) {
return 'Must be 4-15 characters';
}
return null;
},
),
),
],
),
),
),
GestureDetector(
onTap: () {
_determinePosition();
},
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FloatingActionButton(
onPressed: () {
_determinePosition();
},
child: const Icon(Icons.location_on_outlined),
),
const SizedBox(width: 10),
if (position == null)
const Text(
'Press to add location - Required',
style: TextStyle(color: Colors.red),
),
if (position != null)
Text(
'Current location: ${position!.latitude.round()}, ${position!.longitude.round()}')
],
),
),
],
),
),
),
if (_isLoading)
const Opacity(
opacity: 0.8,
child: ModalBarrier(dismissible: false, color: Colors.black),
),
if (_isLoading)
const Center(
child: CircularProgressIndicator(color: Color(0xFFb1bbd8)),
),
],
);
}
}
I appreciate any help with this.

Related

Error : Failed to detect image file format using the file header. File header was [0x3c 0x68 0x74 0x6d 0x6c 0x3e 0x0a 0x20 0x20 0x20]

I'm trying to display an image from Firestore in to my UI. But it returns the error above, and the file format also changes when I run it on Edge (not on physical device or Emulator). I can't figure out how. Here's my code.
class ViewPola extends StatefulWidget {
const ViewPola({Key? key}) : super(key: key);
static String id = 'view_pola';
#override
State<ViewPola> createState() => _ViewPolaState();
}
class _ViewPolaState extends State<ViewPola> {
Function getSnaps = () async {
final polaMap = {
'Kode Pola': '',
'Bagian Pola': '',
'image_url': '',
};
FirebaseFirestore.instance
.collection('PolaWillyJKT')
.limit(1)
.get()
.then((snapshot) {
if (snapshot.size == 0) {
FirebaseFirestore.instance.collection('PolaWillyJKT').add(polaMap);
FirebaseFirestore.instance.collection('PolaWillyJKT');
print('add');
} else {
print('disini nge get');
var a = FirebaseFirestore.instance.collection('PolaWillyJKT').get();
Map<String, dynamic> data = a as Map<String, dynamic>;
print(data);
}
});
};
var _selectedItem;
var _showList = false;
#override
void initState() {
getSnaps();
super.initState();
}
final Stream<QuerySnapshot> _polaWilly =
FirebaseFirestore.instance.collection('PolaWillyJKT').snapshots();
#override
Widget build(BuildContext context) {
final screenHeight = ScreenInfo.screenHeight(context);
final screenWidth = ScreenInfo.screenWidth(context);
return StreamBuilder<QuerySnapshot>(
stream: _polaWilly,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Text('Something went wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Text("Loading");
}
return SafeArea(
child: Scaffold(
body: Padding(
padding: EdgeInsets.all(25),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Text(
'Pilih Bagian Pola',
style: TextStyle(fontSize: 25),
),
const SizedBox(
height: 20,
),
DropdownButton(
isExpanded: true,
value: _selectedItem,
items: snapshot.data?.docs
.map(
(value) => DropdownMenuItem(
value: value.get("Bagian Pola"),
child: Text('${value.get("Bagian Pola")}'),
),
)
.toList(),
onChanged: (newValue) {
setState(() {
_selectedItem = newValue.toString();
_showList = true;
});
}),
Padding(
padding: const EdgeInsets.all(25),
child: Visibility(
visible: _showList,
child: Container(
height: screenHeight * 0.4,
child: ListView(
children: snapshot.data!.docs
.where(
(e) => e.get("Bagian Pola") == _selectedItem)
.map((DocumentSnapshot document) {
Map<String, dynamic> data =
document.data()! as Map<String, dynamic>;
return Center(
child: Column(
children: [
Text(
'Bagian Pola: ${data["Bagian Pola"]}',
style: TextStyle(fontSize: 15),
),
const SizedBox(
height: 15,
),
Text(
'Kode Pola : ${data["Kode Pola"]}',
style: TextStyle(fontSize: 15),
),
const SizedBox(
height: 15,
),
Image(
image:
NetworkImage(document.get("Foto Pola")),
height: 200,
width: 200,
), // this is the Image widget where I tried to put the image from firestore
Text(document.get('Foto Pola').toString()),
],
),
);
}).toList(),
),
),
),
),
],
),
),
),
);
},
);
}
}
and here's the class that uploads the image to Firestore
class Input_Pola extends StatefulWidget {
const Input_Pola({Key? key}) : super(key: key);
static String id = 'input_pola';
#override
State<Input_Pola> createState() => _Input_PolaState();
}
class _Input_PolaState extends State<Input_Pola> {
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
void _checkDuplicate() {
if (options.contains(_textfieldValue.text)) {
// Display bottom sheet that says item already exists
_scaffoldKey.currentState?.showBottomSheet((context) => Container(
height: 300,
child: Column(
children: [
const Text('Item already exists'),
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('Dismiss'))
],
),
));
} else {
// Add item to options list
setState(() {
options.add(_textfieldValue.text);
});
}
}
XFile? image;
final ImagePicker picker = ImagePicker();
String _image_url = '';
void _addToFirebase(String dropdownValue, String _kodePolaController) {
var imageFile = File(image!.path);
String fileName = pth.basename(imageFile.path);
FirebaseStorage storage = FirebaseStorage.instance;
Reference ref = storage.ref().child("WillyJKT/polaWillyJKT");
UploadTask uploadTask = ref.putFile(imageFile);
uploadTask.whenComplete(() async {
var url = await ref.getDownloadURL();
_image_url = url.toString();
});
FirebaseFirestore.instance
.collection('PolaWillyJKT')
.doc(_selectedOption)
.set({
'Bagian Pola': _selectedOption,
'Kode Pola': _kodePolaController,
'Foto Pola': _image_url
});
}
String _dropdownValue = 'kg';
String _property1 = '';
String _property2 = '';
String _property3 = '';
bool _isOptionSelected = false;
final TextEditingController _kodePolaController = TextEditingController();
var _selectedOption;
final TextEditingController _textfieldValue = TextEditingController();
final List<String> options = [];
#override
void initState() {
super.initState();
_selectedOption = options.isNotEmpty ? options[0] : null;
}
//we can upload image from camera or from gallery based on parameter
Future getImage(ImageSource media) async {
var img = await picker.pickImage(source: media);
setState(() {
image = img;
});
}
void myAlert() {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
title: Text('Please choose media to select'),
content: Container(
height: MediaQuery.of(context).size.height / 6,
child: Column(
children: [
ElevatedButton(
//if user click this button, user can upload image from gallery
onPressed: () {
Navigator.pop(context);
getImage(ImageSource.gallery);
},
child: Row(
children: [
Icon(Icons.image),
Text('From Gallery'),
],
),
),
ElevatedButton(
//if user click this button. user can upload image from camera
onPressed: () {
Navigator.pop(context);
getImage(ImageSource.camera);
},
child: Row(
children: [
Icon(Icons.camera),
Text('From Camera'),
],
),
),
],
),
),
);
});
}
#override
Widget build(BuildContext context) {
final screenHeight = ScreenInfo.screenHeight(context);
final screenWidth = ScreenInfo.screenWidth(context);
return SafeArea(
child: Scaffold(
key: _scaffoldKey,
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.add),
onPressed: () {
_addToFirebase(_dropdownValue, _kodePolaController.text);
},
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(25),
child: Container(
height: screenHeight,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
TextFormField(
decoration: const InputDecoration(
hintText: 'Input Pola',
border: UnderlineInputBorder(),
),
onChanged: (value) {
setState(() {
_textfieldValue.text = value;
});
},
),
DropdownButton<String>(
value: _selectedOption,
onChanged: (value) {
setState(() {
_selectedOption = value!;
_isOptionSelected = true;
_kodePolaController.clear();
});
},
hint: const Text('Input from Text Field Above'),
items: options.map((option) {
return DropdownMenuItem<String>(
value: option,
child: Text(option),
);
}).toList(),
),
TextButton(
onPressed: _checkDuplicate,
child: const Text("Add Option"),
),
Visibility(
visible: _isOptionSelected,
child: Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
TextField(
controller: _kodePolaController,
decoration: const InputDecoration(
labelText: "Kode Pola"),
onChanged: (value) {
setState(() {
_property1 = value;
});
},
),
const SizedBox(height: 20,),
ElevatedButton(
onPressed: () {
myAlert();
},
child: Text('Upload Photo'),
),
SizedBox(
height: 10,
),
//if image not null show the image
//if image null show text
image != null
? Padding(
padding:
const EdgeInsets.symmetric(horizontal: 20),
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Image.file(
//to show image, you type like this.
File(image!.path),
fit: BoxFit.cover,
width: MediaQuery.of(context).size.width,
height: 300,
),
),
)
: const Text(
"No Image",
style: TextStyle(fontSize: 20),
),
],
),
),
)
],
),
),
),
),
),
);
}
}
It also displays the error on Edge, but when I build the apk and run it on my physical device, it just shows nothing on the screen except for the data that's got above it. Any idea on how I can fix this?
var a = FirebaseFirestore.instance.collection('PolaWillyJKT').get();
This returns a promise but not the actual data. In fact it could still be fetching the data when you attempt to convert it to a map.
You can await
var a = await FirebaseFirestore.instance.collection('PolaWillyJKT').get();
myDoc = a.docs.first();
Or use a callback that will run once the collection fetch completes:
FirebaseFirestore.instance.collection('PolaWillyJKT').get().then((response) => {
print(response);
});

Store Image in List<Xfile> from image urls

I have created a variable
List<Xfile> imageList;
using this variable I have showed the selected images in GridView.Builder and uploaded them.
But I want to store those uploaded images in this List to show them again in GridView.Builder.
Means How to store images from imageUrls in List
How can I achieve this?
Follow as follows:
Variables
final picker = ImagePicker();
File? file;
XFile? pickedImage;
bool isLoading = false;
List<File?> fileList = [];
Method to select image from gallery
Future pickImageFromGallery() async {
pickedImage = await picker.pickImage(source: ImageSource.gallery);
setState(() {
file = File(pickedImage!.path);
fileList.add(file);
});
}
And place in gridview as follows:
GridView.builder(
itemCount: fileList.length,
gridDelegate:
const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
itemBuilder: (BuildContext context, int i) {
return Container(
padding: const EdgeInsets.all(10),
child: Stack(
children: <Widget>[
SizedBox(
height: 100,
width: 100,
child: Image.file(File(fileList[i]!.path),fit: BoxFit.cover,),
),
Positioned(
right: 1,
child: GestureDetector(
onTap: () {
setState(() {
dltImages(fileList[i]);
});
},
child: const Icon(Icons.cancel, color: Colors.red),
))
],
),
);
},
),
Find full code at:
https://github.com/nbnD/image_picker_flutter/blob/master/lib/homepage.dart
I do like this if there is multi images upload
class PickImagesPage extends StatefulWidget {
const PickImagesPage({super.key, required this.initialUrls});
final List<String> initialUrls;
#override
State<PickImagesPage> createState() => _PickImagesPageState();
}
class _PickImagesPageState extends State<PickImagesPage> {
#override
void initState() {
urls = widget.initialUrls;
super.initState();
}
List<String> urls = [];
List<File> files = [];
List<String> removedUrls = [];
final Repo repo = Repo();
#override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final style = theme.textTheme;
final scheme = theme.colorScheme;
return LoadingLayer(
child: Scaffold(
bottomNavigationBar: Padding(
padding: const EdgeInsets.fromLTRB(24, 0, 24, 24),
child: ElevatedButton(
onPressed:
files.isNotEmpty || widget.initialUrls.length != urls.length
? () async {
try {
await repo.uploadImages(
files: files,
urls: urls,
removedUrls: removedUrls,
);
Navigator.pop(context);
} catch (e) {
AppSnackbar(context).error(e);
if (kDebugMode) {
print(e);
}
}
}
: null,
child: const Text(Labels.save),
),
),
appBar: AppBar(
title: const Text(
Labels.ambienceImages,
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
final List<XFile> pickedFiles = await pickImages();
if (pickedFiles.isNotEmpty) {
setState(() {
files.addAll(pickedFiles.map((e) => File(e.path)));
});
}
},
child: const Icon(Icons.add),
),
body: GridView.count(
padding: const EdgeInsets.all(12),
crossAxisCount: 2,
mainAxisSpacing: 12,
crossAxisSpacing: 12,
children: [
...urls
.map(
(e) => GestureDetector(
onTap: () {
setState(() {
urls.remove(e);
removedUrls.add(e);
});
},
child: Container(
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
color: scheme.surfaceVariant.withOpacity(0.5),
borderRadius: BorderRadius.circular(20),
image: DecorationImage(
image: NetworkImage(e),
),
),
),
),
)
.toList(),
...files
.map(
(e) => Container(
clipBehavior: Clip.antiAlias,
alignment: Alignment.topRight,
decoration: BoxDecoration(
color: scheme.surfaceVariant.withOpacity(0.5),
borderRadius: BorderRadius.circular(20),
image: DecorationImage(
image: FileImage(e),
),
),
child: SizedBox(
height: 40,
width: 40,
child: RawMaterialButton(
elevation: 0,
focusElevation: 0,
hoverElevation: 0,
shape: const CircleBorder(),
fillColor: theme.cardColor.withOpacity(0.5),
onPressed: () {
setState(() {
files.remove(e);
});
},
child: const Icon(Icons.remove),
),
),
),
)
.toList(),
GestureDetector(
onTap: () async {
final List<XFile> pickedFiles = await pickImages();
if (pickedFiles.isNotEmpty) {
setState(() {
files.addAll(pickedFiles.map((e) => File(e.path)));
});
}
},
child: Container(
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
color: scheme.surfaceVariant.withOpacity(0.5),
borderRadius: BorderRadius.circular(20),
),
child: Stack(
children: const [
Center(
child: Icon(Icons.add),
),
PickImageLabel(),
],
),
),
),
],
),
),
);
}
}
class Repo {
Future<void> uploadImages(
{required List<String> urls,
required List<File> files,
required List<String> removedUrls}) async {
List<String> newUrls = [];
for (var file in files) {
final url = await upload(file);
newUrls.add(url);
}
for (var url in removedUrls) {
await deleteImage(url);
}
await saveImages(urls + newUrls);
}
}

Having issue with my favorite button functionality in flutter

I am having an issue with my favorite button. I have connected it with real-time firebase and each time I press the favorite icon it changes the state in firebase either true or false. when I press the heart button it always shows me different output sometimes it becomes red or black without affecting the other and sometimes it changes the other ones too (red or black). I have tried a lot to solve this but I am unable to get a solution for it.
class Home_page extends StatefulWidget {
#override
State<Home_page> createState() => _Home_pageState();
}
class _Home_pageState extends State<Home_page> {
//late StreamSubscription _dailySpecialStream;
var clr = Colors.grey;
//var item;
final List<String> _listItem = [
'assets/audi3.png',
'assets/audi.png',
'assets/audi2.png',
'assets/audi.png',
'assets/audi2.png',
'assets/audi3.png',
];
var name;
var auth1 = FirebaseAuth.instance.currentUser;
Data? c;
late final Value;
List<Data> dataList = [];
List<dynamic> d = [];
List<dynamic> favList = [];
#override
void initState() {
print("object");
super.initState();
print(auth1);
_activateListener();
}
void _activateListener() {
final _database = FirebaseDatabase.instance.ref();
_database.child('user').get().then((snapshot) {
dataList.clear();
favList.clear();
print("hello");
Value = snapshot.value as Map;
final datas = snapshot.children.forEach((element) {
d.add(element.key);
});
for (var k in d) {
//print("");
print(Value[k]['imgUrl']);
print((Value[k]['carName']).runtimeType);
dataList.add(Data(
Value[k]['carName'],
Value[k]['price'],
Value[k]["imgUrl"],
k,
));
if (auth1 != null) {
print(k);
print("auth1");
print(auth1);
DatabaseReference reference = FirebaseDatabase.instance
.ref()
.child("user")
.child(k)
.child("fav")
.child(auth1!.uid)
.child("state");
reference.get().then((s) {
print(s.value);
print("upp is vla");
if (s.value != null) {
if (s.value == true) {
// print(s.value);
// print("true");
favList.add(true);
print(favList);
} else {
//print(s.value);
print("false1");
favList.add(false);
//print(favList);
}
} else {
print("inelse");
favList.add(false);
print(favList);
}
});
}
}
Timer(Duration(seconds: 1), () {
setState(() {
inspect(favList);
});
});
});
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Container(
color: Colors.white,
child: Stack(
children: [
Image.asset(
"assets/top.png",
fit: BoxFit.cover,
),
Column(
children: [
SizedBox(
height: 30,
),
search(context),
SizedBox(
height: 80,
),
Expanded(
child: GridView.count(
crossAxisCount: 2,
crossAxisSpacing: 10,
mainAxisSpacing: 40,
children: List.generate(
dataList.length, (index) => GridDesign(index)).toList(),
)),
],
)
],
),
),
),
);
}
SizedBox GridDesign(int index) {
return SizedBox(
child: Column(
children: [
Stack(
clipBehavior: Clip.none,
children: [
Container(
height: 15.h,
width: 45.w,
margin: EdgeInsets.only(left: 12, top: 12, right: 16),
decoration: BoxDecoration(
// border: Border.all(color: Colors.grey,style: BorderStyle.solid,width: 2),
borderRadius: BorderRadius.circular(5),
image: DecorationImage(
image: NetworkImage(dataList[index].url.toString()),
fit: BoxFit.cover)),
),
Positioned(
bottom: -3,
right: 5,
child: Container(
height: 32,
width: 32,
child: Neumorphic(
padding: EdgeInsets.zero,
style: NeumorphicStyle(
//shape: NeumorphicShape.concave,
boxShape: NeumorphicBoxShape.roundRect(
BorderRadius.circular(50)),
color: Colors.white),
child: favList[index]
? IconButton(
padding: EdgeInsets.zero,
onPressed: () {
if (auth1 != null) {
print(auth1);
print("it's not null");
DatabaseReference favRef = FirebaseDatabase
.instance
.ref()
.child("user")
.child(
dataList[index].uploadId.toString())
.child("fav")
.child(auth1!.uid)
.child("state");
favRef.set(false);
setState(() {
favFun();
});
}
print("object");
},
icon: Icon(
Icons.favorite,
color: Colors.red,
),
)
: IconButton(
padding: EdgeInsets.zero,
onPressed: () {
if (auth1 != null) {
print("it's not null1");
print(auth1);
DatabaseReference favRef = FirebaseDatabase
.instance
.ref()
.child("user")
.child(
dataList[index].uploadId.toString())
.child("fav")
.child(auth1!.uid)
.child("state");
favRef.set(true);
setState(() {
favFun();
});
}
print("object");
},
icon: Icon(
Icons.favorite,
))),
),
),
],
),
SizedBox(
height: 4,
),
Expanded(child: Text(dataList[index].CarName.toString())),
SizedBox(height: 2),
Expanded(
child: Text("R" + dataList[index].price.toString()),
),
SizedBox(height: 3),
Expanded(
child: ElevatedButton(
onPressed: () =>
Get.to(DetailPage(dataList[index].Url, dataList[index].Price)),
child: Text("Details"),
style: ElevatedButton.styleFrom(primary: myColor),
))
],
),
);
}
void favFun() {
final _database = FirebaseDatabase.instance.ref();
_database.child('user').get().then((snapshot) {
favList.clear();
for (var k in d) {
//print("");
if (auth1 != null) {
print(k);
print("auth1");
print(auth1);
DatabaseReference reference = FirebaseDatabase.instance
.ref()
.child("user")
.child(k)
.child("fav")
.child(auth1!.uid)
.child("state");
reference.once().then((DatabaseEvent s) {
print(s.snapshot.value);
print("upp is vla");
if (s.snapshot.value != null) {
if (s.snapshot.value == true) {
// print(s.value);
// print("true");
favList.add(true);
print(favList);
} else {
//print(s.value);
print("false1");
favList.add(false);
//print(favList);
}
} else {
print("inelse");
favList.add(false);
print(favList);
}
});
}
}
Timer(Duration(seconds: 1), () {
setState(() {
//inspect(favList);
});
});
});
}
}
Have a look at the picture to get a better view

flutter display only a percentage of the picture

Hello i would like to show only percentage of the photo I take with my camera. This code allows me to take several photos with the camera of my phone. I can also film. What I would like to do is show me only a percentage of the photos I take. Example 70% on the sides and 80% above and below
Here is the code:
class NoGluecamera extends StatefulWidget {
#override
_CameraScreenState createState() => _CameraScreenState();
}
class _CameraScreenState extends State<NoGluecamera>
with WidgetsBindingObserver {
CameraController? controller;
VideoPlayerController? videoController;
File? _imageFile;
File? _videoFile;
// Initial values
bool _isCameraInitialized = false;
bool _isRearCameraSelected = true;
bool _isVideoCameraSelected = false;
bool _isRecordingInProgress = false;
double _minAvailableExposureOffset = 0.0;
double _maxAvailableExposureOffset = 0.0;
double _minAvailableZoom = 1.0;
double _maxAvailableZoom = 1.0;
// Current values
double _currentZoomLevel = 1.0;
double _currentExposureOffset = 0.0;
FlashMode? _currentFlashMode;
List<File> allFileList = [];
final resolutionPresets = ResolutionPreset.values;
ResolutionPreset currentResolutionPreset = ResolutionPreset.medium;
refreshAlreadyCapturedImages() async {
final directory = await getApplicationDocumentsDirectory();
List<FileSystemEntity> fileList = await directory.list().toList();
allFileList.clear();
List<Map<int, dynamic>> fileNames = [];
fileList.forEach((file) {
if (file.path.contains('.jpg') || file.path.contains('.mp4')) {
allFileList.add(File(file.path));
String name = file.path.split('/').last.split('.').first;
fileNames.add({0: int.parse(name), 1: file.path.split('/').last});
}
});
if (fileNames.isNotEmpty) {
final recentFile =
fileNames.reduce((curr, next) => curr[0] > next[0] ? curr : next);
String recentFileName = recentFile[1];
if (recentFileName.contains('.mp4')) {
_videoFile = File('${directory.path}/$recentFileName');
_imageFile = null;
_startVideoPlayer();
} else {
_imageFile = File('${directory.path}/$recentFileName');
_videoFile = null;
}
setState(() {});
}
}
Future<XFile?> takePicture(
) async {
final CameraController? cameraController = controller;
if (cameraController!.value.isTakingPicture) {
// A capture is already pending, do nothing.
return null;
}
try {
XFile file = await cameraController.takePicture();
return file;
} on CameraException catch (e) {
print('Error occured while taking picture: $e');
return null;
}
}
Future<void> _startVideoPlayer() async {
if (_videoFile != null) {
videoController = VideoPlayerController.file(_videoFile!);
await videoController!.initialize().then((_) {
// Ensure the first frame is shown after the video is initialized,
// even before the play button has been pressed.
setState(() {});
});
await videoController!.setLooping(true);
await videoController!.play();
}
}
Future<void> startVideoRecording() async {
final CameraController? cameraController = controller;
if (controller!.value.isRecordingVideo) {
// A recording has already started, do nothing.
return;
}
try {
await cameraController!.startVideoRecording();
setState(() {
_isRecordingInProgress = true;
print(_isRecordingInProgress);
});
} on CameraException catch (e) {
print('Error starting to record video: $e');
}
}
Future<XFile?> stopVideoRecording() async {
if (!controller!.value.isRecordingVideo) {
// Recording is already is stopped state
return null;
}
try {
XFile file = await controller!.stopVideoRecording();
setState(() {
_isRecordingInProgress = false;
});
return file;
} on CameraException catch (e) {
print('Error stopping video recording: $e');
return null;
}
}
Future<void> pauseVideoRecording() async {
if (!controller!.value.isRecordingVideo) {
// Video recording is not in progress
return;
}
try {
await controller!.pauseVideoRecording();
} on CameraException catch (e) {
print('Error pausing video recording: $e');
}
}
Future<void> resumeVideoRecording() async {
if (!controller!.value.isRecordingVideo) {
// No video recording was in progress
return;
}
try {
await controller!.resumeVideoRecording();
} on CameraException catch (e) {
print('Error resuming video recording: $e');
}
}
void resetCameraValues() async {
_currentZoomLevel = 1.0;
_currentExposureOffset = 0.0;
}
void onNewCameraSelected(CameraDescription cameraDescription) async {
final previousCameraController = controller;
final CameraController cameraController = CameraController(
cameraDescription,
currentResolutionPreset,
imageFormatGroup: ImageFormatGroup.jpeg,
);
await previousCameraController?.dispose();
resetCameraValues();
if (mounted) {
setState(() {
controller = cameraController;
});
}
// Update UI if controller updated
cameraController.addListener(() {
if (mounted) setState(() {});
});
try {
await cameraController.initialize();
await Future.wait([
cameraController
.getMinExposureOffset()
.then((value) => _minAvailableExposureOffset = value),
cameraController
.getMaxExposureOffset()
.then((value) => _maxAvailableExposureOffset = value),
cameraController
.getMaxZoomLevel()
.then((value) => _maxAvailableZoom = value),
cameraController
.getMinZoomLevel()
.then((value) => _minAvailableZoom = value),
]);
_currentFlashMode = controller!.value.flashMode;
} on CameraException catch (e) {
print('Error initializing camera: $e');
}
if (mounted) {
setState(() {
_isCameraInitialized = controller!.value.isInitialized;
});
}
}
#override
void initState() {
// Hide the status bar in Android
SystemChrome.setEnabledSystemUIOverlays([]);
// Set and initialize the new camera
onNewCameraSelected(cameras[0]);
refreshAlreadyCapturedImages();
super.initState();
}
#override
void didChangeAppLifecycleState(AppLifecycleState state) {
final CameraController? cameraController = controller;
// App state changed before we got the chance to initialize.
if (cameraController == null || !cameraController.value.isInitialized) {
return;
}
if (state == AppLifecycleState.inactive) {
cameraController.dispose();
} else if (state == AppLifecycleState.resumed) {
onNewCameraSelected(cameraController.description);
}
}
#override
void dispose() {
controller?.dispose();
videoController?.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
backgroundColor: Colors.black,
body: _isCameraInitialized
? Column(
children: [
AspectRatio(
aspectRatio: 3 / 5,
child: Stack(
children: [
controller!.buildPreview(),
Padding(
padding: const EdgeInsets.fromLTRB(
16.0,
8.0,
16.0,
8.0,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Align(
alignment: Alignment.topRight,
child: Container(
decoration: BoxDecoration(
color: Colors.black87,
borderRadius: BorderRadius.circular(10.0),
),
child: Padding(
padding: const EdgeInsets.only(
left: 4.0,
right: 4.0,
),
child: DropdownButton<ResolutionPreset>(
dropdownColor: Colors.black87,
underline: Container(),
value: currentResolutionPreset,
items: [
for (ResolutionPreset preset
in resolutionPresets)
DropdownMenuItem(
child: Text(
preset
.toString()
.split('.')[1]
.toUpperCase(),
style: TextStyle(
color: Colors.white),
),
value: preset,
)
],
onChanged: (value) {
setState(() {
currentResolutionPreset = value!;
_isCameraInitialized = false;
});
onNewCameraSelected(
controller!.description);
},
hint: Text("Select item"),
),
),
),
),
// Spacer(),
Padding(
padding: const EdgeInsets.only(
right: 8.0, top: 16.0),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10.0),
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
_currentExposureOffset
.toStringAsFixed(1) +
'x',
style: TextStyle(color: Colors.black),
),
),
),
),
Expanded(
child: RotatedBox(
quarterTurns: 3,
child: Container(
height: 30,
child: Slider(
value: _currentExposureOffset,
min: _minAvailableExposureOffset,
max: _maxAvailableExposureOffset,
activeColor: Colors.white,
inactiveColor: Colors.white30,
onChanged: (value) async {
setState(() {
_currentExposureOffset = value;
});
await controller!
.setExposureOffset(value);
},
),
),
),
),
Row(
children: [
Expanded(
child: Slider(
value: _currentZoomLevel,
min: _minAvailableZoom,
max: _maxAvailableZoom,
activeColor: Colors.white,
inactiveColor: Colors.white30,
onChanged: (value) async {
setState(() {
_currentZoomLevel = value;
});
await controller!.setZoomLevel(value);
},
),
),
Padding(
padding: const EdgeInsets.only(right: 8.0),
child: Container(
decoration: BoxDecoration(
color: Colors.black87,
borderRadius:
BorderRadius.circular(10.0),
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
_currentZoomLevel.toStringAsFixed(1) +
'x',
style: TextStyle(color: Colors.white),
),
),
),
),
],
),
Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
InkWell(
onTap: _isRecordingInProgress
? () async {
if (controller!
.value.isRecordingPaused) {
await resumeVideoRecording();
} else {
await pauseVideoRecording();
}
}
: () {
setState(() {
_isCameraInitialized = false;
});
onNewCameraSelected(cameras[
_isRearCameraSelected ? 1 : 0]);
setState(() {
_isRearCameraSelected =
!_isRearCameraSelected;
});
},
child: Stack(
alignment: Alignment.center,
children: [
Icon(
Icons.circle,
color: Colors.black38,
size: 60,
),
_isRecordingInProgress
? controller!
.value.isRecordingPaused
? Icon(
Icons.play_arrow,
color: Colors.white,
size: 30,
)
: Icon(
Icons.pause,
color: Colors.white,
size: 30,
)
: Icon(
_isRearCameraSelected
? Icons.camera_front
: Icons.camera_rear,
color: Colors.white,
size: 30,
),
],
),
),
InkWell(
onTap: _isVideoCameraSelected
? () async {
if (_isRecordingInProgress) {
XFile? rawVideo =
await stopVideoRecording();
File videoFile =
File(rawVideo!.path);
int currentUnix = DateTime.now()
.millisecondsSinceEpoch;
final directory =
await getApplicationDocumentsDirectory();
String fileFormat = videoFile.path
.split('.')
.last;
_videoFile = await videoFile.copy(
'${directory.path}/$currentUnix.$fileFormat',
);
_startVideoPlayer();
} else {
await startVideoRecording();
}
}
: () async {
XFile? rawImage =
await takePicture();
File imageFile =
File(rawImage!.path);
int currentUnix = DateTime.now()
.millisecondsSinceEpoch;
final directory =
await getApplicationDocumentsDirectory();
String fileFormat =
imageFile.path.split('.').last;
print(fileFormat);
await imageFile.copy(
'${directory.path}/$currentUnix.$fileFormat',
);
refreshAlreadyCapturedImages();
},
child: Stack(
alignment: Alignment.center,
children: [
Icon(
Icons.circle,
color: _isVideoCameraSelected
? Colors.white
: Colors.white38,
size: 80,
),
Icon(
Icons.circle,
color: _isVideoCameraSelected
? Colors.red
: Colors.white,
size: 65,
),
_isVideoCameraSelected &&
_isRecordingInProgress
? Icon(
Icons.stop_rounded,
color: Colors.white,
size: 32,
)
: Container(),
],
),
),
InkWell(
onTap:
_imageFile != null || _videoFile != null
? () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) =>
PreviewScreen(
imageFile: _imageFile!,
fileList: allFileList,
),
),
);
}
: null,
child: Container(
width: 60,
height: 60,
decoration: BoxDecoration(
color: Colors.black,
borderRadius:
BorderRadius.circular(10.0),
border: Border.all(
color: Colors.white,
width: 2,
),
image: _imageFile != null
? DecorationImage(
image: FileImage(_imageFile!),
fit: BoxFit.cover,
)
: null,
),
child: videoController != null &&
videoController!
.value.isInitialized
? ClipRRect(
borderRadius:
BorderRadius.circular(8.0),
child: AspectRatio(
aspectRatio: videoController!
.value.aspectRatio,
child: VideoPlayer(
videoController!),
),
)
: Container(),
),
),
],
),
],
),
),
],
),
),
Expanded(
child: SingleChildScrollView(
physics: BouncingScrollPhysics(),
child: Column(
children: [
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Row(
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.only(
left: 8.0,
right: 4.0,
),
child: TextButton(
onPressed: _isRecordingInProgress
? null
: () {
if (_isVideoCameraSelected) {
setState(() {
_isVideoCameraSelected =
false;
});
}
},
style: TextButton.styleFrom(
primary: _isVideoCameraSelected
? Colors.black54
: Colors.black,
backgroundColor: _isVideoCameraSelected
? Colors.white30
: Colors.white,
),
child: Text('IMAGE'),
),
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.only(
left: 4.0, right: 8.0),
child: TextButton(
onPressed: () {
if (!_isVideoCameraSelected) {
setState(() {
_isVideoCameraSelected = true;
});

Keyboard trigger the api call while closing and opening in flutter?

Keyboard triggers the api calling while closing and opening
I have search bar I didn't pass anything inside the search bar but when I click the search bar The api call will run.
I don't know why that thing was happen I tried several ways but It won't work
Even Inside the keyboard I choose the one hand keyboard that time also api will run
Also tried the Focusnode also.
class PopupNaviagator extends StatefulWidget {
var body;
String leadsName = "";
Map<String, dynamic> listValues;
PopupNaviagator(this.listValues);
var data;
String pageData = "";
double totalPageCount = 0;
int pageIncrementer = 1;
#override
_PopupNavigatorState createState() => _PopupNavigatorState();
}
class _PopupNavigatorState extends State<PopupNaviagator> {
Utils util = new Utils();
bool isSearching = false;
#override
void initState() {
super.initState();
}
String searchingText = "";
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
titleSpacing: 0,
flexibleSpace: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: util.getColors(1001),
stops: [0.1, 5.0],
),
),
),
title: !isSearching
? Text("Select Search Type")
: TextField(
autofocus: true,
autocorrect: true,
onChanged: (value) {
searchingText = value;
},
cursorColor: Colors.white,
onSubmitted: (value) {
searchingText = value;
campaignAPI(
widget.listValues["colname"].toString(),
widget.pageIncrementer.toString(),
searchingText, // search key
1, // flag
);
},
style: TextStyle(color: Colors.white),
decoration: InputDecoration(
icon: Icon(Icons.search),
hintText: "Search ",
hintStyle: TextStyle(color: Colors.white)),
),
actions: <Widget>[
isSearching
? IconButton(
icon: Icon(Icons.cancel),
onPressed: () {
setState(() {
searchingText = "";
this.isSearching = false;
campaignAPI(
widget.listValues["colname"].toString(),
widget.pageIncrementer.toString(),
searchingText, // search key
1, // flag
);
/* filteredCountries = countries;*/
});
},
)
: IconButton(
icon: Icon(Icons.search),
onPressed: () {
setState(() {
this.isSearching = true;
});
},
)
],
),
body: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(5))),
child: Scaffold(
body: FutureBuilder(
future: campaignAPI(widget.listValues["colname"].toString(), "1",
searchingText, 0),
builder: (context, snapshot) {
if (snapshot.hasData) {
var body;
if (widget.data == null) {
body = snapshot.data;
} else {
body = widget.data;
}
final records = body["list_records"];
widget.pageData = body["PageValues"];
widget.totalPageCount =
(body["TotalRecordCount"] / 5).toDouble();
return Scaffold(
body: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
if (records.length != 0) ...[
Expanded(
child: ListView.builder(
padding: EdgeInsets.only(
top: 0,
bottom: 0,
),
physics: ClampingScrollPhysics(),
shrinkWrap: true,
itemCount: records.length,
itemBuilder: (context, index) {
Map<String, dynamic> pickerValues =
records[index];
String titleName =
pickerValues["viewcol_value"]
.toString();
return Container(
margin: const EdgeInsets.all(5.00),
decoration: new BoxDecoration(
color: Colors.white,
border: Border.all(
color: Colors.grey, width: 1.0),
borderRadius: new BorderRadius.all(
Radius.circular(3.0)),
),
child: FlatButton(
padding: EdgeInsets.all(8.0),
onPressed: () {
setState(() {
List<String> strArr = [
titleName,
pickerValues["rec_id"].toString(),
widget.listValues["colname"]
];
Navigator.pop(context, strArr);
});
},
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(titleName.toString()),
Icon(
Icons.check_circle_outlined,
color: Colors.grey,
),
]),
),
);
}),
),
] else ...[
Container(
height: MediaQuery.of(context).size.height / 1.4,
child: Center(
child: Container(
padding: EdgeInsets.all(65),
child: Text(
"No Record Found",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
color: Colors.black),
),
decoration: BoxDecoration(
border: Border.all(
color: Colors.grey,
width: 2,
),
)),
),
),
],
if (records.length != 0) ...[
Container(
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
InkWell(
onTap: () {
if (widget.pageIncrementer > 1) {
widget.pageIncrementer--;
campaignAPI(
widget.listValues["colname"]
.toString(),
widget.pageIncrementer.toString(),
searchingText, // search key
1, // flag
);
setState(() {});
} else {
util.showToast("No records to show");
}
},
child: Icon(Icons.arrow_left_rounded,
size: 50, color: Colors.white),
),
Text(
widget.pageData,
style: TextStyle(
fontSize: 15,
color: Colors.white,
fontWeight: FontWeight.bold),
),
InkWell(
onTap: () {
if (widget.totalPageCount > 1 &&
widget.totalPageCount >=
widget.pageIncrementer) {
widget.pageIncrementer++;
campaignAPI(
widget.listValues["colname"]
.toString(),
widget.pageIncrementer.toString(),
searchingText, // search key
1, // flag
);
} else {
util.showToast("No reocrds to show");
}
},
child: Icon(Icons.arrow_right_rounded,
size: 50, color: Colors.white),
),
],
),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: util.getColors(1001),
stops: [0.1, 5.0],
),
),
)
]
],
),
),
);
} else if (snapshot.hasError) {
return Text('${snapshot.error.toString()}');
}
return Center(
child: CircularProgressIndicator(),
);
},
),
),
));
}
campaignAPI(
String field_col, String page_no, String searchValue, int flag) async {
Utils util = new Utils();
SharedPreferences prefs = await SharedPreferences.getInstance();
final accessKey = prefs.getString('access_key');
final companyName = prefs.getString('company_name');
Object requestParam = {
"companyname": companyName,
"access_key": accessKey.toString(),
"field_col": field_col,
"page_no": page_no,
"searchValue": searchValue,
};
print(requestParam.toString());
APIS apis = new APIS();
Uri url = Uri.parse(apis.searchquickcreate);
util.prints(url);
util.prints(requestParam);
final response = await http.post(url, body: requestParam);
if (response.statusCode == 200) {
final body = json.decode(response.body);
print(body);
String status = body["status"];
if (status != "failed") {
if (flag == 1) {
setState(() {
widget.data = body;
});
}
return body;
} else {
util.logOut(context);
return body;
}
} else {
Navigator.pop(context);
util.showToast("Server Error !");
throw Exception("Server Error !");
}
}
}