Among the whole API response string I wants to get only particular word in flutter how to do it? - string

Below is the response where I am getting image path.the file can be pdf or jpeg or any other format. for image i am showing it in dialogue and for pdf I have to download it to the user's device.For that first I have to check where the file is pdf or not for that i wants to get the extension of file format like pdf or jpeg from whole path (shown in 0th and 1st). How to do it using spilt string I have tried several ways but unable to get the result.Please guide me regarding it.
0:"https://xuriti-prod-kyc.s3.ap-south-1.amazonaws.com/27AAACB2100P1ZX/1675230131954-download-%281%29.jpeg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAXALYDECMNE2HOZS7%2F20230216%2Fap-south-1%2Fs3%2Faws4_request&X-Amz-Date=20230216T063528Z&X-Amz-Expires=900&X-Amz-Signature=59204e81b56cd325de1531a1e6c6a67c5030c76c0516b4719e40986e1ef1d917&X-Amz-SignedHeaders=host"
1:"https://xuriti-prod-kyc.s3.ap-south-1.amazonaws.com/27AAACB2100P1ZX/1675230131972-download.jpeg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAXALYDECMNE2HOZS7%2F20230216%2Fap-south-1%2Fs3%2Faws4_request&X-Amz-Date=20230216T063528Z&X-Amz-Expires=900&X-Amz-Signature=867311e96282f231406f46d5f2a5d11befe985b0b3a0ab161f69dfb3465b50a9&X-Amz-SignedHeaders=host"
Below is my code where i tried to split and get the file format:
List imgfiles = [];
#override
void initState() {
init();
super.initState();
}
Future init() async {
dynamic companyId = getIt<SharedPreferences>().getString('companyId');
//final docs = DioClient().KycDetails(companyId);
dynamic responseData = await getIt<DioClient>().KycDetails(companyId);
final details = responseData['data'];
Aadhar Docdetails = Aadhar.fromJson(details['aadhar']);
setState(() {
List<String> imgfiles = Docdetails.files;
this.imgfiles = imgfiles;
});
}
Padding(
padding: EdgeInsets.only(
left: w1p * 3,
right: w1p * 6,
),
child: SizedBox(
width: maxWidth,
height: 50,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: imgfiles.length,
itemBuilder: (context, index) {
String doc = imgfiles[index];
print('the whole filepath >>>>>>>>$doc');
String doc1 = doc.split('jpeg').toString();
print('doc1.>>>>>>>>$doc1');
return GestureDetector(
onTap: () {
showDialog(
context: context,
builder: (context) {
return Dialog(
child: Container(
width: 220,
height: 200,
child: Image.network(
'$doc',
fit: BoxFit.cover,
),
),
);
});
},
child: imageDialog());
},
),
//_checkController();
),
),

just use split and substring
String getExtension(url){
url = url.split('?')[0];
url = url.split('/').last;
return url.contains('.') ? url.substring(url.lastIndexOf('.')+1) : "";
}
Usage,
const url =
"https://xuriti-prod-kyc.s3.ap-south-1.amazonaws.com/27AAACB2100P1ZX/1675230131954-download-%281%29.jpeg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAXALYDECMNE2HOZS7%2F20230216%2Fap-south-1%2Fs3%2Faws4_request&X-Amz-Date=20230216T063528Z&X-Amz-Expires=900&X-Amz-Signature=59204e81b56cd325de1531a1e6c6a67c5030c76c0516b4719e40986e1ef1d917&X-Amz-SignedHeaders=host";
final extension = getExtension(url); // return 'jpeg'
if (extension == "jpeg"){
// show image
}
else if(extension == "pdf") {
// show download option
}

If you are sure response will have consistent format you can try this. Also to be sure you may add a couple of checks on each step to avoid exceptions.
final String input = 'https://xuriti-prod-kyc.s3.ap-south-1.amazonaws.com/27AAACB2100P1ZX/1675230131972-download.jpeg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAXALYDECMNE2HOZS7%2F20230216%2Fap-south-1%2Fs3%2Faws4_request&X-Amz-Date=20230216T063528Z&X-Amz-Expires=900&X-Amz-Signature=867311e96282f231406f46d5f2a5d11befe985b0b3a0ab161f69dfb3465b50a9&X-Amz-SignedHeaders=host';
final res = input.split('/').last.split('?').first.split('.').last;

Instead of splitting you can use regex here:
String getExtension(url){
final regexJpeg = RegExp(r'\.jpeg\?*');
final regexPdf = RegExp(r'\.pdf\?*');
if(regexJpeg.hasMatch(url)){
return 'jpeg';
}
else if(regexPdf.hasMatch(url)){
return 'pdf';
} else{
return 'unknown';
}
}

Related

When Scrolling down I want to hide images from ScrollablePositionedList.builder

ScrollablePositionedList.builder(
itemCount: 100,
itemBuilder: (context, index) {
return Column(
children: [
Image.network(",,,,,,,,")
Text("Item number $index"),
],
);
},
),
I need the Text to be seen on scroll,but how I can hide the images onScroll?
i think some people still struggle with that feature, because its not support for this version.as you can see many people raise for these issue on github.
i just try some alternative from issue#305, its not good enough but you can apply it.
first its not official , so we need to fetch the plugin from other repository. so you need to modify your pubspec.yaml like below:
from this:
dependencies:
scrollable_positioned_list: ^0.3.2
to this:
dependencies:
scrollable_positioned_list:
git:
url: https://github.com/nabil6391/flutter.widgets.git
ref: master
path: packages/scrollable_positioned_list/
after you pub get , then your itemController will be able to access scrollController
so you just add listener to check the scroll direction
class _MyWidgetState extends State<MyWidget> {
final ItemScrollController itemSctr = ItemScrollController();
late bool _isVisible;
#override
void initState() {
_isVisible = true;
itemSctr.scrollController?.addListener(() {
if (itemSctr.scrollController?.position.userScrollDirection ==
ScrollDirection.reverse) {
if (_isVisible == true) {
setState(() {
_isVisible = false;
});
}
} else {
if (itemSctr.scrollController?.position.userScrollDirection ==
ScrollDirection.forward) {
if (_isVisible == false) {
setState(() {
_isVisible = true;
});
}
}
}
});
super.initState();
}
and last on your list you can apply like this
body: Scrollbar(
controller: itemSctr.scrollController, // you need to modify your pubspec.yaml
child: ScrollablePositionedList.builder(
itemCount: 100,
itemPositionsListener: _itemPositionController,
itemScrollController: itemSctr,
itemBuilder: (context, index) {
return Column(
children: [
Visibility(
visible: _isVisible,
child:
Image.network('https://picsum.photos/250?image=9')),
Text(
"Item number $index $_isVisible",
style: const TextStyle(color: Colors.black),
),
],
);
},
),
),
i just tested and its works. but some bug also happend when you scroll to the last index, it cant be show as we want.

Flutter: Animations badly slow down disk write speed

Not sure if this is a bug or just how the things work, or me doing something wrong.
I'm making an app which can parse text files for some data and then store it in a sqlite database. At some point I decided to add basic spinner to indicate that there is parsing in progress, cause it usually takes few seconds on an average file.
So I added a ternary operator which renders CircularProgressIndicator() if isBusy variable is set to true. And my parsing time suddenly increased to about 10 times of what it was before. That's on Linux. On Android it also slows down process but only for additional ~70%. I checked few things and it looks like any animation causes this problem, e.g. AnimatedContainer.
Steps to reproduce:
Run the code below, notice the completion time in dialog.
Uncomment CircularProgressIndicator() or AnimatedContainer block and run the code again. Notice how much longer it takes now.
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
const Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: darkBlue,
),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: MyWidget(),
),
),
);
}
}
class MyWidget extends StatefulWidget {
#override
State<MyWidget> createState() => _MyWidget();
}
class _MyWidget extends State<MyWidget> {
var _width = 50.0;
var _height = 50.0;
void startHeavyOperation() async {
final directory = await getApplicationDocumentsDirectory();
var myFile = File('${directory.path}/test.txt');
const max = 10000;
var x = 0;
setState(() {
_width = 300;
_height = 300;
});
final startTime = DateTime.now();
while (x < max) {
await myFile.writeAsString('$x\n', mode: FileMode.append);
x += 1;
}
final endTime = DateTime.now();
final durationInMilliseconds = endTime.difference(startTime).inMilliseconds;
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: Text('It took $durationInMilliseconds ms'),
),
);
}
#override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () => startHeavyOperation(),
child: const Text('startHeavyOperation'),
),
// AnimatedContainer(
// duration: Duration(seconds: 10),
// child: Text('123'),
// color: Colors.red,
// width: _width,
// height: _height,
// ),
// CircularProgressIndicator(),
],
),
);
}
}
My question is: is there a way to use animations w/o slowing disk writes?
Yeah - I suspect it is the animation indeed. Try putting the heavy operation in an isolate - I suspect that will speed things up (on the device). Here's an example.
That while statement is very expensive even without the animation. Putting in a separate isolate will save you some time. Here is a quick modification to your code example. compute will give you a future.
void startHeavyOperation(String path) async {
var myFile = File('$path/test.txt');
const max = 10000;
var x = 0;
final startTime = DateTime.now();
while (x < max) {
await myFile.writeAsString('$x\n', mode: FileMode.append);
x += 1;
}
final endTime = DateTime.now();
final durationInMilliseconds = endTime.difference(startTime).inMilliseconds;
print('It took $durationInMilliseconds ms');
}
class MyWidget extends StatefulWidget {
#override
State<MyWidget> createState() => _MyWidget();
}
class _MyWidget extends State<MyWidget> {
var _width = 50.0;
var _height = 50.0;
#override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () async {
final directory = await getApplicationDocumentsDirectory();
compute(startHeavyOperation, directory.path);
},
child: const Text('startHeavyOperation'),
),
// AnimatedContainer(
// duration: Duration(seconds: 10),
// child: Text('123'),
// color: Colors.red,
// width: _width,
// height: _height,
// ),
//
CircularProgressIndicator(),
],
),
);
}
}

Dart - Dynamically creating checkboxes with listview is blank unless refreshed

I'm trying to make dynamically created checkboxes with a ListView. If I restart the simulator and go to my search page, the checkboxes aren't there. If I "hot reload" the simulator (ctrl + S) the checkboxes show up. If I go back to the menu and come back to the search page, the checkboxes are gone. If I click on "search" to search for the recipes in my database, the checkboxes reappear. I don't know what's going on here.
Here is my categories map:
Map<String, bool> categoryMap = {};
var checkedCategories = [];
void findCategories() async {
int responseCode = await categories();
print(responseCode);
if(responseCode == 200){
newCategories = categoriesList;
for(int i = 0; i < newCategories.length; i++){
categoryMap.putIfAbsent(newCategories[i]['name'].toString(), () => false);
}
print("new categories of length ${newCategories.length} are: " + newCategories[1]['name'].toString());
print("categoryMap is: " + categoryMap.toString());
} else {
print("Error: unauthorized");
}
}
getCheckedCategories(){
categoryMap.forEach((key, value) {
if(value == true)
{
checkedCategories.add(key);
}
});
// Printing all selected items on Terminal screen.
print(checkedCategories);
print(categoryMap.keys);
// Here you will get all your selected Checkbox items.
// Clear array after use.
checkedCategories.clear();
}
#override
void initState() {
super.initState();
findCategories();
print('hi there');
}
And here is where I am trying to show the checkboxes:
child: Column(
children: [
SizedBox(height: 40.0,),
new ListView(
scrollDirection: Axis.vertical,
shrinkWrap: true,
children: categoryMap.keys.map((String key) {
//print("here is a new checkbox!");
return new CheckboxListTile(
title: new Text(key),
value: categoryMap[key],
activeColor: Colors.pink,
checkColor: Colors.white,
onChanged: (bool value) {
setState(() {
categoryMap[key] = value;
});
},
);
}).toList(),
),
isLoading ? Center(
child: CircularProgressIndicator(),
) : new RaisedButton(
child: Text('Search'),
color: Colors.orange[600],
textColor: Colors.white,
onPressed: () async {
setState(() {
isLoading = true; //Data is loading
});
/*int response_code = await categories();
print(response_code);*/
clearResults();
await getRecipe(searchController.text);
Navigator.push(context, MaterialPageRoute(builder: (context)=>RecipeResultsPage()));
/*if(response_code == 200){
await getRecipe(searchController.text);
Navigator.push(context, MaterialPageRoute(builder: (context)=>RecipeResultsPage()));
} else {
print("Error: unauthorized");
}*/
},
),
Here is a demonstration of the bug (notice how the checkboxes disappear if I go back to the menu and come back to the search page):
Also notice how the checkboxes appear if I click on the search button
Try wrapping the code where you update categoryMap in a setState like this:
setState(() {
for(int i = 0; i < newCategories.length; i++){
categoryMap.putIfAbsent(newCategories[i]['name'].toString(), () => false);
}
});

Insert an image StaggeredGridView that is upload by the user !! The argument type 'File' can't be assigned to the parameter type 'String'

I want to create a StaggeredGridView and fill it with images that the user uploads. The problem is that the type of StaggeredGridView is String or ImageProvider<Object> and the file is PickedFile or File
What is the solution ??
class GalleryClassOneState extends State<GalleryClassOne> {
List<File> arrayImage = [];
File sampleImage;
final _picker = ImagePicker();
// #override
// void initState() {
// super.initState();
// DatabaseReference images =
// FirebaseDatabase.instance.reference().child("NeuralNetwork");
// }
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Galeria clase 1'),
),
body: Container(padding: EdgeInsets.all(8), child: galeria(arrayImage)),
floatingActionButton: FloatingActionButton(
onPressed: _optionsDialogBox,
tooltip: 'Pick Image',
child: Icon(Icons.add_outlined),
),
);
}
Widget galeria(List<File> arrayImage) {
return StaggeredGridView.countBuilder(
crossAxisCount: 4,
itemCount: 11,
itemBuilder: (BuildContext context, int index) {
return ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Container(
color: Colors.deepPurple,
child: Column(
children: <Widget>[
Image.network(arrayImage[index])
],
),
),
);
},
// staggeredTileBuilder: (int index) => new StaggeredTile.fit(1),
staggeredTileBuilder: (int index) =>
new StaggeredTile.count(2, index.isEven ? 2 : 1),
mainAxisSpacing: 10.0,
crossAxisSpacing: 10.0,
);
}
}
We will need to work with the images as bytes instead of files. First, make arrayImage a List<Uint8List>. Here we will store a list of the byte arrays representing an image loaded in memory. Update the galeria() method to accept a List<Uint8List> as well.
Now in the optionsDialogBox() method, we will use the results of the _picker like so:
_picker.getImage(source: ImageSource.gallery).then((pickedFile) {
// read the bytes from the PickedFile
pickedFile.readAsBytes().then((bytes) {
// add the image as bytes to the arrayImage list and update the UI
setState(() => arrayImage.add(bytes));
});
});
When we create our Image widget, we will use the Image.memory() constructor passing to it the bytes representing our image.
Image.memory(arrayImage[index])

how to create conditional statement with string in Flutter?

I am trying to create an app with a flutter on android studio 3.5.2, everything is fully updated,
the concept is this, There is a text field, and a Submit button,
and within the submit button, three strings/text needs to be valid to get inside,
if somebody typed a word that won't match it will show, no words exist,
for example,
Strings - Philippines, Dubai, Japan
if {
textfield does not match string,
Show text hint - Does not match data,
}
Else
{
Welcome from "string"
}
I'm still new, and I know this is not the exact code, but I hope somebody can help me translate this for flutter code, thank you to whoever will help.
Try this,
import 'package:flutter/material.dart';
class Question1 extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _Question1State();
}
}
class _Question1State extends State<Question1> {
TextEditingController _textController = TextEditingController();
String infoText = '';
List<String> countryList = [
'philippines',
'dubai',
'japan',
];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Padding(
padding: EdgeInsets.all(20.0),
child: Column(
children: <Widget>[
TextField(
controller: _textController,
decoration: InputDecoration(
hintText: 'Enter Country',
),
),
SizedBox(
height: 25.0,
),
FlatButton(
onPressed: () {
_validateUserInput(_textController.text);
},
child: Text('Submit'),
color: Colors.blue,
),
SizedBox(
height: 25.0,
),
Text(
infoText,
style: TextStyle(color: Colors.red),
),
],
),
),
);
}
_validateUserInput(String input) {
if (!countryList.contains(input.toLowerCase())) {
setState(() {
infoText = 'Does not match data';
});
} else {
setState(() {
infoText = 'Welcome from $input';
});
}
}
}
Declare a list of string you need to match,
List<String> mList = ['philippines', 'dubai', 'japan'];
then match your textfiled string like this,
var myStr = 'dubai';//or your textFieldController.text
if (mList.contains(myStr)) {
print('Welcome from ${myStr}');
} else {
print('Does not match data');
}
Or as #Rahul Patel Suggested in his answer you do it by ternary operator,
mList.contains(myStr) ? print('Welcome from ${myStr}') : print('Does not match data');
You can use a ternary operator to solve this issue, it is a simple condensed syntax for a conditional if else. The syntax is as follows:
(some conditional || or other conditional && required conditional)?someMethodToHandleSuccess:someMethodToHandleFailure
The (conditional)?ifTrue:ifFalse is the general syntax. Hope this helps!

Resources