Flutter数据过滤插件where_not_null的使用

Flutter数据过滤插件where_not_null的使用

where_not_null 是一个用于 Iterable<T?> 的扩展方法,它将 Iterable<T?> 转换为 Iterable<T>。由于 Dart 类型系统的原因,这种转换变得有些复杂。

示例代码

以下是一个完整的示例代码,展示了如何在 Flutter 应用中使用 where_not_null 插件。

import 'package:flutter/material.dart';
import 'package:where_not_null/where_not_null.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('where_not_null 示例'),
        ),
        body: Center(
          child: ExampleWidget(),
        ),
      ),
    );
  }
}

class ExampleWidget extends StatefulWidget {
  @override
  _ExampleWidgetState createState() => _ExampleWidgetState();
}

class _ExampleWidgetState extends State<ExampleWidget> {
  List<int?> _list = [1, 2, null, 4, null];

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text(
          '原始列表: ${_list.join(", ")}',
          style: TextStyle(fontSize: 18),
        ),
        SizedBox(height: 20),
        ElevatedButton(
          onPressed: () {
            int sum = _list.whereNotNull().reduce((a, b) => a + b);
            setState(() {
              _list = [sum];
            });
          },
          child: Text('计算非空元素之和'),
        ),
        SizedBox(height: 20),
        Text(
          '计算结果: ${_list.join(", ")}',
          style: TextStyle(fontSize: 18),
        ),
      ],
    );
  }
}

解释

  1. 导入必要的包

    import 'package:flutter/material.dart';
    import 'package:where_not_null/where_not_null.dart';
    
  2. 定义主应用类 MyApp

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: Text('where_not_null 示例'),
            ),
            body: Center(
              child: ExampleWidget(),
            ),
          ),
        );
      }
    }
    
  3. 定义示例组件 ExampleWidget

    class ExampleWidget extends StatefulWidget {
      @override
      _ExampleWidgetState createState() => _ExampleWidgetState();
    }
    
    class _ExampleWidgetState extends State<ExampleWidget> {
      List<int?> _list = [1, 2, null, 4, null];
    
      @override
      Widget build(BuildContext context) {
        return Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              '原始列表: ${_list.join(", ")}',
              style: TextStyle(fontSize: 18),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                int sum = _list.whereNotNull().reduce((a, b) => a + b);
                setState(() {
                  _list = [sum];
                });
              },
              child: Text('计算非空元素之和'),
            ),
            SizedBox(height: 20),
            Text(
              '计算结果: ${_list.join(", ")}',
              style: TextStyle(fontSize: 18),
            ),
          ],
        );
      }
    }
    

更多关于Flutter数据过滤插件where_not_null的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter数据过滤插件where_not_null的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中,whereNotNull 是一个非常有用的方法,用于过滤掉集合中的 null 值。它通常用于处理可能包含 null 值的列表或其他集合类型。

使用 whereNotNull

whereNotNullIterable 的一个扩展方法,可以在 dart:collection 库中找到。它的作用是返回一个不包含 null 值的迭代器。

基本用法

假设你有一个包含 null 值的列表,你可以使用 whereNotNull 来过滤掉这些 null 值:

import 'package:collection/collection.dart';

void main() {
  List<String?> names = ['Alice', 'Bob', null, 'Charlie', null, 'David'];

  // 使用 whereNotNull 过滤掉 null 值
  List<String> nonNullNames = names.whereNotNull().toList();

  print(nonNullNames); // 输出: [Alice, Bob, Charlie, David]
}

处理复杂类型

whereNotNull 也可以用于处理包含复杂类型(如对象)的列表,过滤掉其中为 null 的元素:

class Person {
  final String name;

  Person(this.name);
}

void main() {
  List<Person?> people = [
    Person('Alice'),
    null,
    Person('Bob'),
    null,
    Person('Charlie')
  ];

  // 使用 whereNotNull 过滤掉 null 值
  List<Person> nonNullPeople = people.whereNotNull().toList();

  print(nonNullPeople.map((person) => person.name).toList()); // 输出: [Alice, Bob, Charlie]
}

注意事项

  1. 导入库whereNotNullpackage:collection/collection.dart 的一部分,因此在使用之前需要导入该库。

    import 'package:collection/collection.dart';
回到顶部