【问题标题】:Get value and set in bottom navigation in Flutter在 Flutter 的底部导航中获取值并设置
【发布时间】:2021-01-02 08:45:38
【问题描述】:

我需要获取一个购物车值并在 Flutter 底部导航中添加为徽章,但在函数之后没有设置值

我的代码

void _getCartValue() {
      getCartcount().then((value) => {print(value), cartlength = value});
      // setState(() {});
    }

    _getCartValue();

底部导航代码

 BottomNavigationBarItem(
        label: 'Cart',
        icon: Badge(
          shape: BadgeShape.circle,
          borderRadius: BorderRadius.circular(100),
          child: Icon(Icons.shopping_cart),
          badgeContent: Container(
            height: 15,
            width: 15,
            decoration:
                BoxDecoration(shape: BoxShape.circle, color: Colors.red),
            child: Text(
              cartlength.toString(),
              style: TextStyle(
                  color: Colors.white,
                  fontSize: 10,
                  fontWeight: FontWeight.bold),
            ),
          ),
        ),
      ),

该值正在函数内部打印,但我无法获取函数下方的值。帮我将值从_getCartValue 传递到cartlength

函数下方出现空值

【问题讨论】:

    标签: flutter


    【解决方案1】:

    您无法更改异步执行主体内的外部变量值 ..then, ..whenComple, ..catchError
    也许你可以试试这个

    void _getCartValue() async {
      try {
        final value = await getCartCount();
        cartlength = value;
        // setState(() {});
      } catch (_) {}
    }
    
    _getCartValue();
    

    编辑
    一个干净的方法是像这样用FutureBuilder 包装你的Text 小部件

    FutureBuilder(
      future: getCartCount,
      builder: (context, snapshot) {
        return ConnectionState.done == snapshot.connectionState ? Text(
          snapshot.data.toString(),
          style: TextStyle(
              color: Colors.white,
              fontSize: 10,
              fontWeight: FontWeight.bold),
        ) : SizedBox(width: 10.0, height: 10.0, child: CircularProgressIndicator());
      },
    ),
    

    【讨论】:

    • 当我打印它作为 'Future' 的实例的值时
    • 老板打印你的值前缀await。例如:print(await _getCartValue());
    • 如何在底部导航中传递该值很好
    • 最终值 = await getCartcount();我正在尝试这样,但值为 null
    • 我在getCartCount 上错误地省略了await。用这个重试
    猜你喜欢
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    • 2020-12-17
    相关资源
    最近更新 更多