我正在使用提供程序进行状态管理.当我在另一个类中使用provider调用nullable(int?tipIndex)变量时,我必须输入!操作人员当我把!opertaor我得到一个错误,null check opertaor对null值使用...如何在初始阶段保持变量为null.

以下是提供程序类代码:

 int? tipIndex;
  List<double> tipList = [2, 3, 5];

在这里,我将从ListView中为tipIndex分配索引的值.建设者

setState(() {
               cart.tipIndex = index;
               });

这里我使用的是值

cart.tipList[index] == cart.tipList[cart.tipIndex!]

下面是完整的列表视图生成器

ListView.builder(
  scrollDirection: Axis.horizontal,
  itemCount: cart.tipList.length,
  shrinkWrap: true,
  itemBuilder: ((context, index) {
    return tipContainer(context, cart.tipList[index].toInt(),
        () {
      setState(() {
        cart.tipIndex = index;
      });
    },
        cart.tipList[index] == cart.tipList[cart.tipIndex]
            ? const Color.fromARGB(255, 243, 164, 1)
                .withOpacity(0.5)
            : Colors.black54,
        cart.tipList[index] == cart.tipList[cart.tipIndex]
            ? Colors.white
            : Colors.transparent);
  }),
);

Here is UI

推荐答案

在实际使用之前,您应该有条件地通过判断cart.tipIndex是否为null来构建UI.它将是以下内容:

ListView.builder(
  scrollDirection: Axis.horizontal,
  itemCount: cart.tipList.length,
  shrinkWrap: true,
  itemBuilder: ((context, index) {
    return tipContainer(
      context,
      cart.tipList[index].toInt(),
      () {
        setState(() {
          cart.tipIndex = index;
        });
      },
      // Here
      cart.tipIndex != null && cart.tipList[index] == cart.tipList[cart.tipIndex!]
          ? const Color.fromARGB(255, 243, 164, 1)
              .withOpacity(0.5)
          : Colors.black54,
      // Here
      cart.tipIndex != null && cart.tipList[index] == cart.tipList[cart.tipIndex!]
          ? Colors.white
          : Colors.transparent,
    );
  }),
);

Flutter相关问答推荐

文本未设置在集装箱摆动的中心

我有相关的下拉菜单Flutter Windows应用程序的问题

在选项卡栏视图中搜索和筛选不起作用

将Riverpods NotifierProvider与State类一起使用

Android工作室Flutter 热重新加载更新后不工作

了解多Provider 和流

在 flutter 的列中使用 Expanded 时出现渲染 Flex 错误

Flutter记录返回类型问题

如果有空间则居中CustomScrollView

在Flutter中为容器实现线性渐变背景动画

为什么我们需要使用ChangeNotifierProvider而不是仅仅使用ChangeNotifier?

splash_screen 没有被推送到登录页面

Flutter 应用程序在启动画面冻结(java.lang.RuntimeException:无法启动活动 ComponentInfo)

setState 方法有时有效,有时无效

从子集合sem中获取参考学年&&课程名称的值

当我使用 Confetti Widget 时,Flutter Android 和 IOS 应用程序崩溃

flutter - 无法解析 JSON 消息:文档为空

Flutter 在气泡聊天消息上对齐时间戳文本

如何使用 Riverpod 在运行时动态创建提供程序?

如何从 Flutter 中的列表中提取 JSON?