Flutter Daily Development Tips

Beck Moulton
4 min readMay 6, 2024

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 extensionkeyword. Its purpose is to improve the readability and maintainability of the code.

In the following example, a method called capitalize ()is added to the Stringtype 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 extensionsdirectly 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…

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

Responses (1)