Flutter Map的基本使用

我们先点进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()));
  }
}

这时候我们就可以一起管理了,减少多余代码,更加优雅简洁

有时候我们需要分别管理,例如1,2需要改变,  3,4又有其他改变,这时候我们可以这样做



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()),
    );
  }
}

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值