我们先点进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<String, int> map2 = Map();
map2["map1"] = 1;
print(map2); //{a8: 1}
//改变一个键值对
map2['a8'] = 2;
print(map2); //{a8: 2}
map还可以这样使用:
class _MyApp1State extends State<MyApp1> {
@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()));
}
}
这时候我们就可以一起管理了,减少多余代码,更加优雅简洁文章来源:https://www.toymoban.com/news/detail-543611.html
有时候我们需要分别管理,例如1,2需要改变, 3,4又有其他改变,这时候我们可以这样做文章来源地址https://www.toymoban.com/news/detail-543611.html
class MyApp1 extends StatefulWidget {
const MyApp1({Key? key}) : super(key: key);
@override
_MyApp1State createState() => _MyApp1State();
}
class _MyApp1State extends State<MyApp1> {
@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()),
);
}
}
到了这里,关于Flutter Map的基本使用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!