如何在Flutter中跳过List<dynamic>中的Null值

huangapple go评论63阅读模式
英文:

How to skip Null value from List<dynamic> in flutter

问题

以下是您提供的代码的中文翻译:

// 忽略文件的警告: prefer_const_constructors, prefer_const_literals_to_create_immutables

import 'package:campuslib/controllers/content_controller.dart';
import 'package:campuslib/utils/colors.dart';
import 'package:campuslib/utils/dimensions.dart';
import 'package:campuslib/utils/routers.dart';
import 'package:campuslib/widgets/big_text.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

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

  @override
  State<DepartmentBody> createState() => _DepartmentBodyState();
}

class _DepartmentBodyState extends State<DepartmentBody> {
  final ContentController _contentController = Get.put(ContentController());

  late Map<String, String> deptFullName = {
    "cse": "计算机科学与工程",
    "eee": "电气与电子工程",
    "math": "数学",
    "sta": "统计学",
    "nonacademic": "非学术",
    "islamic": "伊斯兰学",
    "acce": "应用化学与化学工程",
  };

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      if (!(_contentController.dept.value.data != null)) {
        return CircularProgressIndicator();
      } else {
        var deptList = _contentController.dept.value.data?.getDepartments;
        return _initDeptBody(deptList);
      }
    });
  }

  Widget _initDeptBody(var deptList) {
    return Expanded(
      child: Column(
        children: [
          SizedBox(
            height: 20,
          ),
          BigText(
            text: "部门",
            fontWeight: FontWeight.bold,
            size: 20,
          ),
          Obx(() => (!_contentController.isLoadingForDept.value)
              ? Expanded(
                  child: Container(
                    padding: EdgeInsets.fromLTRB(20, 15, 20, 0),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(40),
                        topRight: Radius.circular(40),
                      ),
                    ),
                    child: ListView.builder(
                      itemCount: deptList?.length,
                      padding: EdgeInsets.zero,
                      physics: BouncingScrollPhysics(),
                      shrinkWrap: true,
                      itemBuilder: (context, index) =>
                          _buildDepartmentItem(deptList, index),
                    ),
                  ),
                )
              : CircularProgressIndicator())
        ],
      ),
    );
  }

  Widget _buildDepartmentItem(var deptList, int index) {
    final String? currentString = deptList[index];
    if (currentString != null) {
      return Container(
        height: Dimension.deptNameContainer(context),
        margin: EdgeInsets.fromLTRB(0, 0, 0, 20),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(15),
          child: Stack(
            alignment: AlignmentDirectional.center,
            children: [
              Container(
                width: MediaQuery.of(context).size.width,
                decoration: BoxDecoration(
                  image: DecorationImage(
                    fit: BoxFit.cover,
                    image: AssetImage("assets/images/${deptList[index]}.jpg"),
                  ),
                ),
              ),
              Card(
                elevation: 0.0,
                margin: EdgeInsets.zero,
                color: Color.fromARGB(202, 25, 24, 24),
                child: Container(
                  height: MediaQuery.of(context).size.height,
                  width: MediaQuery.of(context).size.width,
                  child: InkWell(
                    onTap: () {
                      // 导航到部门路线
                      Get.toNamed(MyRouters.departmentRoute, arguments: {
                        "deptBanner": deptList[index],
                        "deptName": deptFullName[deptList[index]],
                      });
                    },
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        ListTile(
                          title: Text(
                            deptFullName[deptList?[index]]!,
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              color: AppColors.lightColor,
                              fontWeight: FontWeight.w500,
                              // fontSize: 18,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      );
    } else {
      return Container();
    }
  }
}

希望这个翻译对您有所帮助。如果您需要任何进一步的协助,请随时告诉我。

英文:

Summary:<br/>
I have a List of dynamic data such as {"CSE", "EEE", null, "ACCE"}.
Now I want to show these data through ListView builder except the null.
But I can't skip the null value. It gives:

Exception has occurred. (type &#39;Null&#39; is not a subtype of type &#39;String&#39; in type cast)

My code is given below and I tried other method too, which I give in the screenshots.

// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables
import &#39;package:campuslib/controllers/content_controller.dart&#39;;
import &#39;package:campuslib/utils/colors.dart&#39;;
import &#39;package:campuslib/utils/dimensions.dart&#39;;
import &#39;package:campuslib/utils/routers.dart&#39;;
import &#39;package:campuslib/widgets/big_text.dart&#39;;
import &#39;package:flutter/foundation.dart&#39;;
import &#39;package:flutter/material.dart&#39;;
import &#39;package:get/get.dart&#39;;
class DepartmentBody extends StatefulWidget {
const DepartmentBody({Key? key}) : super(key: key);
@override
State&lt;DepartmentBody&gt; createState() =&gt; _DepartmentBodyState();
}
class _DepartmentBodyState extends State&lt;DepartmentBody&gt; {
final ContentController _contentController = Get.put(ContentController());
late Map&lt;String, String&gt; deptFullName = {
&quot;cse&quot;: &quot;Computer Science and Engineering&quot;,
&quot;eee&quot;: &quot;Electrical and Electronic Engineering&quot;,
&quot;math&quot;: &quot;Mathematics&quot;,
&quot;sta&quot;: &quot;Statistics&quot;,
&quot;nonacademic&quot;: &quot;Non Academic&quot;,
&quot;islamic&quot;: &quot;Islamic&quot;,
&quot;acce&quot;: &quot;Applied Chemistry &amp; Chemical Engineering&quot;,
};
@override
Widget build(BuildContext context) {
return Obx(() {
if (!(_contentController.dept.value.data != null)) {
return CircularProgressIndicator();
} else {
var deptList = _contentController.dept.value.data?.getDepartments;
return _initDeptBody(deptList);
}
});
}
Widget _initDeptBody(var deptList) {
return Expanded(
child: Column(
children: [
SizedBox(
height: 20,
),
BigText(
text: &quot;Departments&quot;,
fontWeight: FontWeight.bold,
size: 20,
),
Obx(() =&gt; (!_contentController.isLoadingForDept.value)
? Expanded(
child: Container(
padding: EdgeInsets.fromLTRB(20, 15, 20, 0),
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(40),
topRight: Radius.circular(40),
),
),
child: ListView.builder(
itemCount: deptList?.length,
padding: EdgeInsets.zero,
physics: BouncingScrollPhysics(),
shrinkWrap: true,
itemBuilder: (context, index) =&gt;
_buildDepartmentItem(deptList, index),
),
),
)
: CircularProgressIndicator())
],
),
);
}
Widget _buildDepartmentItem(var deptList, int index) {
final String? currentString = deptList[index];
if (currentString != null) {
return Container(
height: Dimension.deptNameContainer(context),
margin: EdgeInsets.fromLTRB(0, 0, 0, 20),
child: ClipRRect(
borderRadius: BorderRadius.circular(15),
child: Stack(
alignment: AlignmentDirectional.center,
children: [
Container(
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
image: AssetImage(&quot;assets/images/${deptList[index]}.jpg&quot;),
),
),
),
Card(
elevation: 0.0,
margin: EdgeInsets.zero,
color: Color.fromARGB(202, 25, 24, 24),
child: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: InkWell(
onTap: () {
// Navigator.name(context, MyRouters.departmentRoute);
Get.toNamed(MyRouters.departmentRoute, arguments: {
&quot;deptBanner&quot;: deptList[index],
&quot;deptName&quot;: deptFullName[deptList[index]],
});
},
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ListTile(
title: Text(
deptFullName[deptList?[index]]!,
textAlign: TextAlign.center,
style: TextStyle(
color: AppColors.lightColor,
fontWeight: FontWeight.w500,
// fontSize: 18,
),
),
),
],
),
),
),
),
],
),
),
);
} else {
return Container();
}
}
}

Screenshots:

如何在Flutter中跳过List<dynamic>中的Null值

Flutter doctor:
如何在Flutter中跳过List<dynamic>中的Null值

答案1

得分: 1

你可以筛选掉空值,将它们转换为列表,如下所示:

List<String> validDeptList = deptList?.where((dept) => dept != null).toList() ?? [];

以这种方式,validDeptList 只包含非空值。

英文:

You can filter the null value to cast them in the list like

List&lt;String&gt; validDeptList = deptList?.where((dept) =&gt; dept != null).toList() ?? [];

In this form, validDeptList have only non-null values.

huangapple
  • 本文由 发表于 2023年7月18日 10:17:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76709142.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定