我们先点进Map中查看代码:
可以看到这里需要两个值分别是 K和V
关于Map对象,通过{}初始化Map对象,每个元素形式为Key:Value
键(Key)和值(Value)之间使用冒号" : "分割
元素之间使用分号";"分割
基本使用方式:
Map student = {1: "Tm1", 2: "Jr1", 3: "spk1"}; print(student); //{1: Tm, 2: Jr, 3: spk}
先创建Map 对象在进行赋值
Map president = {}; president[1] = "Tm2"; president[2] = "Jr2"; president[3] = "spk2"; print(president); //{1: Tm2, 2: Jr2, 3: spk2}
常见属性:
Map map1 = Map(); map1["map1"] = 1; map1["map2"] = 2; map1["map3"] = 3; print(map1.length); //长度 print(map1.isEmpty); //是否为空 print(map1.isNotEmpty); //是否不为空
常见方法:
//常见使用方法 //新增一个键值对 Map map2 = Map(); map2["map1"] = 1; print(map2); //{a8: 1} //改变一个键值对 map2['a8'] = 2; print(map2); //{a8: 2}
map还可以这样使用:
class _MyApp1State extends State { @override Widget build(BuildContext context) { return Scaffold( body: Column( children: [ Container( color: Colors.blue, width: 100, height: 100, ), Container( color: Colors.green, width: 100, height: 100, ), Container( color: Colors.red, width: 100, height: 100, ) ].map((Widget widget) { return SizedBox( child: widget, ); }).toList())); }}
这时候我们就可以一起管理了,减少多余代码,更加优雅简洁
有时候我们需要分别管理,例如1,2需要改变, 3,4又有其他改变,这时候我们可以这样做
class MyApp1 extends StatefulWidget { const MyApp1({Key? key}) : super(key: key); @override _MyApp1State createState() => _MyApp1State();}class _MyApp1State extends State { @override Widget build(BuildContext context) { return Scaffold( body: Column( children: [ Container( key: ValueKey('1'), width: 500, height: 500, color: Colors.green.withOpacity(.2), ), Container( key: ValueKey('2'), width: 500, height: 500, color: Colors.red.withOpacity(.2), ), Container( key: ValueKey('3'), width: 500, height: 500, color: Colors.blue.withOpacity(.2), ), ].map((Widget widget) { double w = 100; double h = 100; if (widget.key == Key('1')) { w = 50; h = 50; } else if (widget.key == Key('2')) { w = 100; h = 100; } else if (widget.key == Key('3')) { w = 150; h = 150; } return SizedBox( width: w, height: h, child: widget, ); }).toList()), ); }}
来源地址:https://blog.csdn.net/a3244005396/article/details/127669603