Flutter get file name - flutter

String fileName = _profPic.path.split('/').last;
print(fileName);
Output is Screenshot_2020-05-12-17-14-07-564_com.miui.home.png
but I require only home.png

It's impossible path or dart can decide which parts of the name you need.
You must manipulate the string. In your case, this method will do what you need:
String getName(String fullName){
final parts = fullName.split('.');
return parts.skip(parts.length - 2).take(2).join('.');
}
example:
final name = 'Screenshot_2020-05-12-17-14-07-564_com.miui.home.png';
print(getName(name)); // home.png
Or, you can convert this method into an extension.

Related

Remove locale from NFC record

I want to pass a text value from my NFC tag to a variable, but want to remove the locale from the text passed to the variable (note, not remove it from the tag).
I am using the nfc_manager package.
Here is the code portion I am using that relates to scanning the tag:
NfcManager.instance.startSession(
onDiscovered: (NfcTag tag) async {
final ndef = Ndef.from(tag);
String tagRecordText = String.fromCharCodes(ndef!.cachedMessage!.records[0].payload);
NfcManager.instance.stopSession();
}
)
The first byte is the length of the characters of the language string
So this should work (my dart is not that good)
var payload = ndef!.cachedMessage!.records[0].payload;
var sub = payload.sublist(payload[0]+ 1);
String tagRecordText = String.fromCharCodes(sub);
The detail specs of a Text Record

How to display Unicode Smiley from json response dynamically in flutter

How to display Unicode Smiley from json response dynamically in flutter. It's display properly when i declare string as a static but from dynamic response it's not display smiley properly.
Static Declaration: (Working)
child: Text("\ud83d\ude0e\ud83d\ude0eThis is just test notification..\ud83d\ude0e\ud83d\ude0e\ud83d\udcaf\ud83d\ude4c")
Dynamic Response:
"message":"\\ud83d\\ude4c Be Safe at your home \\ud83c\\udfe0",
When i'm parse and pass this response to Text then it's consider Unicode as a String and display as a string instead of Smiley Code is below to display text with smiley:
child: Text(_listData[index].message.toString().replaceAll("\\\\", "\\"))
Already go through this: Question but it's only working when single unicode not working with multiple unicode.
Anyone worked with text along with unicode caracter display dynamically then please let me know.
Another alternate Good Solution I would give to unescape characters is this:
1st ->
String s = "\\ud83d\\ude0e Be Safe at your home \\ud83c\\ude0e";
String q = s.replaceAll("\\\\", "\\");
This would print and wont be able to escape characters:
\ud83d\ud83d Be Safe at your home \ud83c\ud83d
and above would be the output.
So what one can do is either unescape them while parsing or use:
String convertStringToUnicode(String content) {
String regex = "\\u";
int offset = content.indexOf(regex) + regex.length;
while(offset > 1){
int limit = offset + 4;
String str = content.substring(offset, limit);
// print(str);
if(str!=null && str.isNotEmpty){
String uni = String.fromCharCode(int.parse(str,radix:16));
content = content.replaceFirst(regex+str,uni);
// print(content);
}
offset = content.indexOf(regex) + regex.length;
// print(offset);
}
return content;
}
This will replace and convert all the literals into unicode characters and result and output of emoji:
String k = convertStringToUnicode(q);
print(k);
😎 Be Safe at your home 🈎
That is above would be the output.
Note: above answer given would just work as good but this is just when you want to have an unescape function and don't need to use third-party libraries.
You can extend this using switch cases with multiple unescape solutions.
Issue resolved by using below code snippet.
Client client = Client();
final response = await client.get(Uri.parse('YOUR_API_URL'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
final extractedData = json.decode(response.body.replaceAll("\\\\", "\\"));
}
Here we need to replace double backslash to single backslash and then decode JSON respone before set into Text like this we can display multiple unicode like this:
final extractedData = json.decode(response.body.replaceAll("\\",
"\"));
Hope this answer help to other

Extracting String in Regex in Flutter and Converting it To Int

I have this Flutter bit of code here, which is a large String. It would be different every time, but the format would stay the same since it's a template:
"William\nWilliam description here...\n$^170^ usd" + Uuid().v4()
I want to extract the 170 part, and then convert it to interger, so I can remove it from list of ints. I have tried a lot of code, but it isn't working for a few reasons, one is I can't extract the actual number from the String between the ^ and ^, and then I can't convert it to interger. Here's the try function (incomplete).
deleteSumItem(item) {
final regEx = RegExp(r'\^\d+(?:\^\d+)?'); //not sure if this is right regex for the String template
final priceValueMatch = regEx.firstMatch(item); //this doesn't return the particular number extracted
_totalPrice.remove(priceValueMatch); //i get error here that it isn't a int
_counter = _counter - priceValueMatch; //then remove it from interger as int
}
The function would take that String ("William\nWilliam description here...\n$^170^ usd" + Uuid().v4()) template (the number would be different between the ^ ^, but the template is same), then convert it to interger and remove from list as int.
Try the following:
void main() {
RegExp regExp = RegExp(r'\^(\d+)\^');
String input = r"William\nWilliam description here...\n$^170^ usd";
String match = regExp.firstMatch(input).group(1);
print(match); // 170
int number = int.parse(match);
print(number); // 170
}
I have changed the RegExp so it does correctly capture the number in its own capture group. It looked like you got a little confused in the process of creating the RegExp but it could also be I am missing some details about the problem.

How to get type of file?

I'm trying to find a package which would recognise file type. For example
final path = "/some/path/to/file/file.jpg";
should be recognised as image or
final path = "/some/path/to/file/file.doc";
should be recognised as document
You can make use of the mime package from the Dart team to extract the MIME types from file names:
import 'package:mime/mime.dart';
final mimeType = lookupMimeType('/some/path/to/file/file.jpg'); // 'image/jpeg'
Helper functions
If you want to know whether a file path represents an image, you can create a function like this:
import 'package:mime/mime.dart';
bool isImage(String path) {
final mimeType = lookupMimeType(path);
return mimeType.startsWith('image/');
}
Likewise, if you want to know if a path represents a document, you can write a function like this:
import 'package:mime/mime.dart';
bool isDocument(String path) {
final mimeType = lookupMimeType(path);
return mimeType == 'application/msword';
}
You can find lists of MIME types at IANA or look at the extension map in the mime package.
From file headers
With the mime package, you can even check against header bytes of a file:
final mimeType = lookupMimeType('image_without_extension', headerBytes: [0xFF, 0xD8]); // jpeg
There is no need of any extension. You can try below code snippet.
String getFileExtension(String fileName) {
return "." + fileName.split('.').last;
}
If think you should take a look to path package, specially to extension method.
You can get file format without adding one more package to pubspec.yaml ;)
context.extension('foo.bar.dart.js', 2); // -> '.dart.js
context.extension('foo.bar.dart.js', 3); // -> '.bar.dart.js'
context.extension('foo.bar.dart.js', 10); // -> '.bar.dart.js'
context.extension('path/to/foo.bar.dart.js', 2); // -> '.dart.js'

How to get the key value from a string when we use FlutterSecureStorage?

I have the following String:
String readToken = await storage.read(key: 'token');
print(readToken);
The output will be:
flutter: "{\"accessToken\":\"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImFiNWUwYzcwMjYwNWU1MjRmMmZkOTQ2NTAwMDQyZDk1MzBlZWZhYjhkYjA0ZGZjYj<…>
The problem is that the readToken value is a String value so I become in a Map like this.
String decoded = jsonDecode(readToken);
And the output is:
flutter: {"accessToken":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImFiNWUwYzcwMjYwNWU1MjRmMmZkOTQ2NTAwMDQyZDk1MzBlZWZhYjhkYjA0ZGZjYjIwMWM1ZmE2NjJjOTQxNTA4OTg1MTZhZjBjNmIyYjRkIn0.eyJhdWQiOiIyIiwianRpIjoiYWI1ZTBjNzAyNjA1ZTUyNGYyZmQ5<…>
So it looks like is a Map value but it isn't, because is still a String.
I would like to get just the value for access_token.
I tried
String dec = decoded.replaceAll(RegExp('"'), '');
int pos = dec.indexOf(':');
final token = dec.substring(pos + 1);
You need to decode your string to transform it to an actual Map.
For that you need to use dart:convert package and do the following: json.decode(variable).
I would also suggest to store only the token value in FlutterSecureStorage and not the entire object.