In Flutter (Dart), you can use the sort method on a list of objects, along with a custom comparator function, to sort the list by the alphabetical order of one of its properties.
Here’s an example of how you can sort a list of objects (let’s say they’re called Person) by their name property:
List<Person> people = [
Person(name: "Bob"),
Person(name: "Charlie"),
Person(name: "Alice"),
];
people.sort((a, b) => a.name.compareTo(b.name));
In this example, the sort method takes a comparator function as its argument. The comparator function compares two Person objects and returns a negative, zero, or positive value, depending on whether the first object should be sorted before, in the same position as, or after the second object. In this case, it compares the name property of each object using the compareTo method and sorts them alphabetically.
Another way to sort by one property is to use the sortBy method from the ‘dart:collection’ package:
There are different concepts that improve the data handling in Dart. The following list of snippets is a collection of the most handy once. Warning: this might simplify your code a lot! 😉
The Spread Operator
Dart supports the spread operator, which allows to insert a collection (multiple elements) into a collection:
The code snippet below merges two maps. All (key) values in default are available in the merged map. This snippet only works for single level maps, multidimensional maps are only handled on the first level:
To set a default value for a nullable variable, you can use the “if null” operator ‘??’:
const defaultValue = "Default";
final someVar = null;
var expectingValue = someVar ?? defaultValue;
print(expectingValue);
// "Default"
if and for in Collections
Dart offers an easy way to create dynamic lists by using conditionals (if) and repetition (for):
var nav = [
'Home',
'Furniture',
'Plants',
if (promoActive) 'Outlet'
];
var listOfInts = [1, 2, 3];
var listOfStrings = [
'#0',
for (var i in listOfInts) '#$i'
];
assert(listOfStrings[1] == '#1');
String to Number
var stringValue = "123";
var intValue = int.parse(stringValue);
print(intValue);
// 123 (int)
var stringValue = "123.45";
var doubleValue = double.parse(stringValue);
print(doubleValue);
// 123.45 (double)
Numbers to String
Most of the Dart data types support a toString() method, which allows a conversion to strings. This is very handy for every parameter where a string is needed:
int intValue = 123;
var stringValue = intValue.toString();
print(stringValue);
// "123" (string)
Check if object exists in list
To check if an object is already in a list, you can use the .where() method. It checks and creates a list based on given conditions. So if the result is not empty then that item exists.
var list = List<MyObject>[];
var myObject = MyObject();
if (list.where((element) => element.optionId == myObject.optionId).isNotEmpty) {
print('object exists');
} else {
print('object does not exist');
}
In my case, a simple app should automatically use the theme (light or dark) of the system to style the user interface. By default, this should work when using ThemeMode.system (see flutter documentation). But it didn’t.
Removing this line solved the issue. This setting sets the apps theme to Light, which results in a constant value even if the user changed the brightness to dark. Without this line, UIUserInterfaceStyle depends on the global setting.
The full documentation for this is available on flutter.dev
When creating json_serializable classes the first time, you’ll get errors similar to what is shown in the image below.
These errors are entirely normal and are simply because the generated code for the model class does not exist yet. To resolve this, run the code generator that generates the serialization boilerplate.
There are two ways of running the code generator.
One-time code generation
By running
flutter pub run build_runner build
in the project root, you generate JSON serialization code for your models whenever they are needed. This triggers a one-time build that goes through the source files, picks the relevant ones, and generates the necessary serialization code for them.
While this is convenient, it would be nice if you did not have to run the build manually every time you make changes in your model classes.
Generating code continuously
A watcher makes our source code generation process more convenient. It watches changes in our project files and automatically builds the necessary files when needed. Start the watcher by running
flutter pub run build_runner watch
in the project root.
It is safe to start the watcher once and leave it running in the background.