flutter 抖音,如何根据未来价值返还不同的widget?

jdgnovmf  于 2023-02-09  发布在  Flutter
关注(0)|答案(2)|浏览(140)

我想根据一个未来的bool值,来设置不同的图标传递回数据卡里面的一个列表,我试过了,然后还是FutureBuilder,但是还是不成功。
支架:

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

数据卡:

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),
                  ),
                ],
              ),

设置收藏夹图标:

Widget setFavouriteIcon(_id) {
  final marked = markedFavourites(_id).then((value) {  //markedFavourites returns 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('');  //Without this line, Error: A non-null value must be returned
}}
k5ifujac

k5ifujac1#

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

Widget setFavouriteIcon(_id) {
  return FutureBuilder(
    future: markedFavourites(_id),// you shouldn't call method directly here on statefulWidget case
    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,
        );
      }
    },
  );
}
svdrlsy4

svdrlsy42#

您应该使用FutureBuilder

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

// some future value
  Future<bool> markedFavorites() async {
//do smth 
    return true;
// or return 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);
          }
        },
      ),
    );
  }
}

相关问题