Flutter 从数据库值异步设置颜色

Flutter to Set Color from Database value Asynchronously

我有这样的场景。

  1. http 调用将从服务器获取数据作为列表
  2. 我必须遍历列表才能显示具有特定颜色的容器
  3. 根据数据库值 (sqlite) 选择颜色
  4. 当尝试从异步函数设置颜色时它不起作用

    Future<Color> _getColor(id) async {
        Color myColor;
        myColor = await helper.queryColor(id);
        return myColor;
     }
    
    
    
    for(int i=0;i<list.length;i++) {
        Container(
        color: await _getColor(list.id);
         )}
    

但显示错误参数类型'Future'无法分配给参数类型'Color'。

由于您的 _getColor 被定义为 Future/Async 函数,因此您需要将其作为可等待函数来调用。

for(int i=0;i<list.length;i++) { Container( color: await _getColor(list.id), ); }

终于在Future Builder

的帮助下实现了我想要的
 child: FutureBuilder<Color>(
      future: _getColor(message[i].sId), //This function return color from Sqlite DB Asynchronously
      builder: (BuildContext context, AsyncSnapshot<Color> snapshot) {
        if (snapshot.hasData) {
          return Card(color: snapshot.data);
        }
        else
         return CupertinoActivityIndicator();
      });