【问题标题】:How to perform null check on map? I'm not getting it如何在地图上执行空检查?我不明白
【发布时间】:2022-01-26 08:02:10
【问题描述】:
// ignore_for_file: prefer_const_constructors

import 'package:flutter/material.dart';
import 'package:world_time/pages/loading.dart';

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  Map data = {};

  @override
  Widget build(BuildContext context) {
    final data = ModalRoute.of(context)?.settings.arguments;
    

    return Scaffold(
      body: SafeArea(
          child: Column(
        children: [
          TextButton.icon(
            onPressed: () {
              Navigator.pushNamed(context, '/choose_location');
            },
            label: Text("Edit location"),
            icon: Icon(Icons.edit_location_alt_sharp),
          ),
                                   // ERROR  
          Text(data['location']), // The method '[]' can't be unconditionally invoked because the 
                                       receiver can be 'null'.
                                       Try making the call conditional (using '?.') or adding a 
                                       null check to the target ('!')
        ],
      )),
    );
  }
}

【问题讨论】:

    标签: flutter dart-null-safety


    【解决方案1】:

    可以从map key中获取null值,可以使用默认值

    Text(data['location']??"default value")
    

    或者在它为空时忽略构建小部件。

    if(data['location']!=null)Text(data['location'])
    

    查看更多关于null-safet的信息。

    【讨论】:

      猜你喜欢
      • 2015-04-30
      • 1970-01-01
      • 1970-01-01
      • 2019-03-03
      • 1970-01-01
      • 1970-01-01
      • 2012-08-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多