Flutter Daily Development Tips
Collected some tips or syntactic sugar that are commonly used in daily development to simplify code and improve development efficiency.
Function extension
In Dart
, we can extend any data type, and any function can be converted to a data type. Therefore, we can also extend any type of function in Dart
. Function extension is achieved by extending methods by using the extension
keyword. Its purpose is to improve the readability and maintainability of the code.
In the following example, a method called capitalize ()
is added to the String
type to capitalize the first letter of the string.
extension StringExtensions on String {
String capitalize() {
if (isEmpty) {
return this;
}
return substring(0, 1).toUpperCase() + substring(1);
}
}class DartTipsPage extends StatefulWidget {
const DartTipsPage({Key? key}) : super(key: key); @override
State<DartTipsPage> createState() => _DartTipsPageState();
}class _DartTipsPageState extends State<DartTipsPage> {
@override
void initState() {
super.initState(); String text = "hello";
print(text.capitalize()); // 输出 "Hello"
}
}
You can also create extensions
directly to the function type to add functionality on top of the function. As an example, add deferred call functionality to the function type.
extension on VoidCallback {
Future<void> delayedCall(
Duration duration,
) =>
Future<void>.delayed(duration, this);
}class…