Flutter,如何根据Future的值返回不同的小部件?

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

Flutter, how to return different widget based on future value?

问题

我想要基于一个未来的布尔值,来设置不同的图标传递给列表中的数据卡,我尝试了`.then`或`FutureBuilder`,但仍然没有成功。

Scaffold:

```dart
child: ListView.builder(
  itemCount: fullList.length,
  itemBuilder: (BuildContext context, int index) {
    return dataCard(context, fullList, index);
  }),

dataCard:

Row(
  children: [
    Expanded(
      flex: 8,
      child: Text(dl[i].Name,
          style:
              TextStyle(color: Colors.blue[400], fontSize: 16)),
    ),
    Expanded(
      flex: 1,
      child: setFavouriteIcon(dl[i].ID),
    ),
  ],
),

setFavouriteIcon:

Widget setFavouriteIcon(_id) {
  final marked = markedFavourites(_id).then((value) {  // markedFavourites 返回 Future<bool>
    if (value == true) {
      return Icon(
        size: 24,
        Icons.favorite,
        color: Colors.red,
      );
    } else {
      return Icon(
        size: 24,
        Icons.favorite_border_outlined,
        color: Colors.red,
      );
    }
  });
  return Text('');  // 没有这一行,会出错:必须返回非空值
}
英文:

I would like to base on a future bool value, to set different icons pass back to a data card inside a list, I tried .then or FutureBuilder, but still not successful.

Scaffold:

child: ListView.builder(
                    itemCount: fullList.length,
                    itemBuilder: (BuildContext context, int index) {
                      return dataCard(context, fullList, index);
                    }),

dataCard:

Row(
                children: [
                  Expanded(
                    flex: 8,
                    child: Text(dl[i].Name,
                        style:
                            TextStyle(color: Colors.blue[400], fontSize: 16)),
                  ),
                  Expanded(
                    flex: 1,
                    child: setFavouriteIcon(dl[i].ID),
                  ),
                ],
              ),

setFavouriteIcon:

Widget setFavouriteIcon(_id) {
  final marked = markedFavourites(_id).then((value) {  //markedFavourites returns Future&lt;bool&gt;
    if (value == true) {
      return Icon(
        size: 24,
        Icons.favorite,
        color: Colors.red,
      );
    } else {
      return Icon(
        size: 24,
        Icons.favorite_border_outlined,
        color: Colors.red,
      );
    }
  });
  return Text(&#39;&#39;);  //Without this line, Error: A non-null value must be returned
}}

答案1

得分: 1

您可以在FutureBuilder上包含其他状态

Widget setFavouriteIcon(_id) {
  return FutureBuilder(
    future: markedFavourites(_id), // 不应该直接在这里调用方法,特别是在StatefulWidget的情况下
    builder: (context, snapshot) {
      final value = snapshot.hasData && (snapshot.data as bool? ?? false);
      if (value == true) {
        return Icon(
          size: 24,
          Icons.favorite,
          color: Colors.red,
        );
      } else {
        return Icon(
          size: 24,
          Icons.favorite_border_outlined,
          color: Colors.red,
        );
      }
    },
  );
}
英文:

You can include other state as well on FutureBuilder

Widget setFavouriteIcon(_id) {
  return FutureBuilder(
    future: markedFavourites(_id),// you shouldn&#39;t call method directly here on statefulWidget case
    builder: (context, snapshot) {
      
      final value = snapshot.hasData &amp;&amp; (snapshot.data as bool? ?? false);
      if (value == true) {
        return Icon(
          size: 24,
          Icons.favorite,
          color: Colors.red,
        );
      } else {
        return Icon(
          size: 24,
          Icons.favorite_border_outlined,
          color: Colors.red,
        );
      }
    },
  );
}

答案2

得分: 0

你应该使用FutureBuilder

class FavoriteWidget extends StatelessWidget {
  const FavoriteWidget({super.key});

  // 一些未来的值
  Future<bool> markedFavorites() async {
    // 做一些操作
    return true;
    // 或者返回false
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: FutureBuilder<bool>(
        future: markedFavorites(),
        builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
          if (snapshot.hasData) {
            if (snapshot.data!) {
              return const Icon(
                Icons.favorite,
                color: Colors.red,
              );
            }
            return const Icon(Icons.favorite_border_outlined);
          }
        },
      ),
    );
  }
}
英文:

you should use FutureBuilder

class FavoriteWidget extends StatelessWidget {
  const FavoriteWidget({super.key});


// some future value
  Future&lt;bool&gt; markedFavorites() async {
//do smth 
    return true;
// or return false 
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: FutureBuilder&lt;bool&gt;(
        future: markedFavorites(),
        builder: (BuildContext context, AsyncSnapshot&lt;bool&gt; snapshot) {
          if (snapshot.hasData) {
            if (snapshot.data!) {
              return const Icon(
                Icons.favorite,
                color: Colors.red,
              );
            }
            return const Icon(Icons.favorite_border_outlined);
          }
        },
      ),
    );
  }
}

huangapple
  • 本文由 发表于 2023年2月6日 10:19:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75356821.html
匿名

发表评论

匿名网友

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

确定