I have two files named
abc.dart
String one = "One";
String two = "Two";
and xyz.dart
String one = "1";
String two = "2";
In my app, I have a bool value, if it is true I want to use one as "One" and if false, one should be "1".
That is I need to import abc.dart on true and xyz.dart on false.
According to this issue, it seems there is not possible in Flutter.
This is because a Flutter app is compiled AOT (ahead of time), so it needs to load all the sources at compile time.
So, instead of counting on dynamic modules imports, your options are:
using compile time constants
// letter.dart
class Letters {
final String one;
final String two;
const Letter(this.one, this.two);
}
// abc.dart
const ABC = Letters('one', two');
// xyz.dart
const XYZ = Letters('1', 2');
// main
import './abc.dart'
import './xyz.dart'
onPressedHandler() {
print(boolValue? abc.one : xyz.one);
}
specify the files as assets and parse them in run time.documentation about using assets
Related
For interaction with an API, I need to pass the course code in <string><space><number> format. For example, MCTE 2333, CCUB 3621, BTE 1021.
Yes, the text part can be 3 or 4 letters.
Most users enter the code without the space, eg: MCTE2333. But that causes error to the API. So how can I add a space between string and numbers so that it follows the correct format.
You can achieve the desired behaviour by using regular expressions:
void main() {
String a = "MCTE2333";
String aStr = a.replaceAll(RegExp(r'[^0-9]'), ''); //extract the number
String bStr = a.replaceAll(RegExp(r'[^A-Za-z]'), ''); //extract the character
print("$bStr $aStr"); //MCTE 2333
}
Note: This will produce the same result, regardless of how many whitespaces your user enters between the characters and numbers.
Try this.You have to give two texfields. One is for name i.e; MCTE and one is for numbers i.e; 1021. (for this textfield you have to change keyboard type only number).
After that you can join those string with space between them and send to your DB.
It's just like hack but it will work.
Scrolling down the course codes list, I noticed some unusual formatting.
Example: TQB 1001E, TQB 1001E etc. (With extra letter at the end)
So, this special format doesn't work with #Jahidul Islam's answer. However, inspired by his answer, I manage to come up with this logic:
var code = "TQB2001M";
var i = course.indexOf(RegExp(r'[^A-Za-z]')); // get the index
var j = course.substring(0, i); // extract the first half
var k = course.substring(i).trim(); // extract the others
var formatted = '$j $k'.toUpperCase(); // combine & capitalize
print(formatted); // TQB 1011M
Works with other formats too. Check out the DartPad here.
Here is the entire logic you need (also works for multiple whitespaces!):
void main() {
String courseCode= "MMM 111";
String parsedCourseCode = "";
if (courseCode.contains(" ")) {
final ensureSingleWhitespace = RegExp(r"(?! )\s+| \s+");
parsedCourseCode = courseCode.split(ensureSingleWhitespace).join(" ");
} else {
final r1 = RegExp(r'[0-9]', caseSensitive: false);
final r2 = RegExp(r'[a-z]', caseSensitive: false);
final letters = courseCode.split(r1);
final numbers = courseCode.split(r2);
parsedCourseCode = "${letters[0].trim()} ${numbers.last}";
}
print(parsedCourseCode);
}
Play around with the input value (courseCode) to test it - also use dart pad if you want. You just have to add this logic to your input value, before submitting / handling the input form of your user :)
I am using sembast package for local data storage for a flutter app. When I search through the local data, I want to get the results regardless of whether letters are in caps or small. My current code is sensitive to capital and small letters.
Future searchFoodByField(String fieldName, String searchItem) async {
var finder = Finder(filter: Filter.matches(fieldName, searchItem));
final recordSnapshots = await _foodStore.find(
await _db,
finder: finder,
);
return recordSnapshots.map((snapshot) {
final food = Food.fromMap(snapshot.value);
food.foodId = snapshot.key;
return food;
}).toList();
}
How can it be modified to get the desired outcome?
I'm assuming you want to look for the exact word. For non-english language, you might also want to remove the accent. (diacritic package can help help here).
// Using a regular expression matching the exact word (no case)
var filter = Filter.matchesRegExp(
fieldName, RegExp('^$searchItem\$', caseSensitive: false));
You can also use a custom filter, to perform any filtering you want:
// Using a custom filter exact word (converting everything to lowercase)
searchItem = searchItem.toLowerCase();
filter = Filter.custom((snapshot) {
var value = snapshot[fieldName] as String;
return value?.toLowerCase() == searchItem;
});
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.
I can load one file and traverse it with babel, it goes something like this:
var babylon = require("babylon");
let contents = fs.readFileSync("example.js","utf-8");
let ast = babylon.parse(contents);
Now the question is, how can I get the AST (Abstract Syntax Tree) if I have multiple files in my program.
main.js
export const getFoo(){
return "a"
}
example.js
import {getFoo} from './main'
let bar = getFoo() + "baz";
Obviously I would like to see the function declaration and the function call expression into the same AST, but also at the same time getting the line numbers and columns (node.loc) information to also show the specific file.
You can concatenate the AST from several files if you know their paths and can load them.
import {parse} from '#babel/parser';
const a = 'var a = 1;'; // or fs.readFileSync("a.js","utf-8");
const b = 'var b = 2;'; // or fs.readFileSync("b.js","utf-8");
const astA = parse(a, { sourceFilename: 'a.js' });
const astB = parse(b, { sourceFilename: 'b.js' });
const ast = {
type: 'Program',
body: [].concat(astA.program.body, astB.program.body)
};
Source example
But I can't find out how to get AST from several files without loading them directly. I tried to write a babel plugin to analyze code from an imported file and I haven't realized how to do that.
when interacting with a rest api using Angular 2. Is it worth creating typescript classes for each object (eg. employee, company, project, user ...). the other option is getting json object and working with it on the fly ?
i suggest using models because :
your code will be more readable for yourself after a while coming back to change it, every one else also can easily understand what you've done
making changes in project will be more easily for example obj[0] does not have any special meaning but obj['username'] is more obvious
you will get intellinsense in you IDE
you can put logic in model for example so your controller will be more thin
name: string
age: number
sayInfo(): string {
return `name is ${this.name} and age is ${this.age}`
}
generally managing you app will be without headache (or at least less headache) :D
just remember that fat models thin controllers
don't forget that passing more than five arguments to a function is not a good practice use an object instead for example :
constructor(file) {
this.id = file['id']
this.fileName = file['fileName']
this.extention = file['extention']
this.fileSize = file['fileSize']
this.permission = file['permission']
this.description = file['description']
this.password = file['password']
this.isFolder = file['isFolder']
this.parent = file['parent']
this.banStat = file['banStat']
this.tinyLink = file['tinyLink']
}
getName(): string {
return `${this.fileName}${(this.isFolder) ? '' : '.'}${this.extention}`
}
getIcon(): string {
return this.isFolder ? 'fa-folder' : 'fa-music'
}