var 和 dynamic
var
未赋初值时,默认值为null
,赋值后数据类型可变。
1 2 3 4
| var variable; print(variable); variable = '我是字符串' variable = 10.00
|
dynamic
未赋初值时,默认值为null
,赋值后数据类型可变,同var
。
List.map()
常用情景:一个对象列表,要将列表中所有对象的某个属性提取出来进行某些操作,生成一个新的列表:
1 2
| List<UserModel> userList = [UserModel(name: '张三', age: 20), UserModel(name: '李四', age: 18)]; List<String> nameList = userList.map((user) => user.name).toList();
|
Flutter为何采用Dart语言?Dart优势何在?
类型拓展方法
1 2 3 4
| extension DividerExtension on int { SizedBox vGap => SizedBox(height: this); }
|
用例:
1 2 3 4 5 6 7 8 9
| Column(children: [ const Text('太阴'), 20.vGap, const Text('太阳'), 20.vGap, const Text('少阴'), 20.vGap, const Text('少阳'), ]);
|
Dart中的工厂模式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| import 'package:flutter/material.dart';
class DebugButton extends StatelessWidget { const DebugButton({ super.key, required this.text, this.onPressed, this.backgroundColor, });
final String text; final void Function()? onPressed; final Color? backgroundColor;
const factory DebugButton.primary({ required String text, Color? backgroundColor, void Function()? onPressed, }) = _DebugPrimaryButton;
@override Widget build(BuildContext context) { return OutlinedButton( onPressed: () => onPressed?.call(), style: OutlinedButton.styleFrom( padding: const EdgeInsets.symmetric(horizontal: 50, vertical: 20), backgroundColor: backgroundColor, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)), ), child: Text(text), ); } }
class _DebugPrimaryButton extends DebugButton { const _DebugPrimaryButton({ required super.text, super.backgroundColor, super.onPressed, });
@override Widget build(BuildContext context) { return ElevatedButton( onPressed: () => onPressed?.call(), style: ElevatedButton.styleFrom( padding: const EdgeInsets.symmetric(horizontal: 50, vertical: 20), backgroundColor: backgroundColor, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)), ), child: Text(text), ); } }
|
参观我的个人网站:http://saoke.fun