【问题标题】:How to save a state of button in a ListTile and make the button async?如何在 ListTile 中保存按钮状态并使按钮异步?
【发布时间】:2020-07-21 20:17:16
【问题描述】:

我尝试向具有保存功能的 ListTile 添加一个按钮。 为了实现保存功能,我需要一个帖子 ID,以便我可以分配从 ListTileTree 传递的正确标题。

此时的问题是它是一个最终值。于是我用谷歌找到了这个Stackoverflow - How to resolve “Only static members can be accessed in initializers” in flutter?

我使用最后一个答案将其置于 Init 状态,但现在出现异常,例如“getter 'scrollOffsetCorrection' 被调用为 null。 接收者:null"。

我该如何解决这个问题?

这是导致错误的部分:

class PostState extends State<_Post> {
  final PostModel post;

  PostState({
    Key key,
    @required this.post,
  })  : assert(post != null),
        super();

  static bool liked = false;

  @override
  void initState() {
    bool _liked = IsLiked.initializeLike(post.postId);
    liked = _liked;
  }

  _pressed() async {
    if (liked == true) {
      setState(() {
        liked = false;
      });
      IsLiked.deleteLike(post.postId);
    } else {
      liked = true;
      IsLiked.like(post);
      setState(() {
        liked = true;
      });
    }

    final directory = await getApplicationDocumentsDirectory();
  }

  @override
  Widget build(BuildContext context) {
    return IconButton(
      icon: new Icon(liked ? Icons.favorite : Icons.favorite_border,
          color: liked ? Colors.red : Colors.grey),
      onPressed: () => _pressed(),
    );
  }

IsLiked.initializeLike(post.postId) 实际上只返回 false,因为没有保存收藏夹

更新:我认为解决方案的一部分是 Future Builder,因为 IsLiked.initializeLike(post.postId) 是异步的,所以我实现了一个返回图标按钮的 Future Builder。现在的问题是我得到另一个错误:“尾随小部件消耗整个瓷砖宽度。请使用尺寸小部件。” 一些可以帮助我的想法或链接?

这是我的新解决方案的代码:

@override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: IsLiked.initializeLike(post.postId),
      builder: (BuildContext context, AsyncSnapshot<dynamic> snap){
        print(liked);
        return IconButton(
          icon: new Icon(liked ? Icons.favorite : Icons.favorite_border,
              color: liked ? Colors.red : Colors.grey),
          onPressed: () => _pressed(),
        );
      },
    );

更新2: 好吧,我找到了一个几乎可行的解决方案。把喜欢当作未来。 但现在的问题是,我如何比较未来的状态是真还是假?

更新代码:

static Future<bool> _liked = test();

  static Future<bool> test() async{
    final directory = await getApplicationDocumentsDirectory();
    return false;
  }
  static bool liked = false;

 @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _liked,
      builder: (BuildContext context, AsyncSnapshot<bool> snapshot){
        if(snapshot.hasData){
          return IconButton(
            icon: new Icon(liked ? Icons.favorite : Icons.favorite_border,
                color: liked ? Colors.red : Colors.grey, size: 30),
            onPressed: () => _pressed(),
          );
        }else{
          return CircularProgressIndicator(
            backgroundColor: Hexcolor("#FFFFFF"),
            valueColor: new AlwaysStoppedAnimation<Color>(Hexcolor('#FE2E2E')));
        }
      },
    );

  }

这是整个班级。

import 'package:Kontra/api/models.dart';
import 'package:Kontra/pages/articel.dart';
import 'package:Kontra/utils/is_liked.dart';
import 'package:Kontra/utils/picture_revision.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:path_provider/path_provider.dart';

class Post extends StatelessWidget {
  final PostModel post;

  const Post({
    Key key,
    @required this.post,
  })  : assert(post != null),
        super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListTile(
      leading: CachedNetworkImage(
        imageUrl: PictureRevision.revisePicture(post.pictures),
        placeholder: (context, url) => CircularProgressIndicator(
          backgroundColor: Hexcolor("#FFFFFF"),
          valueColor: new AlwaysStoppedAnimation<Color>(Hexcolor('#FE2E2E')),
        ),
        errorWidget: (context, url, error) => Icon(Icons.error),
        width: 60.0,
        height: 60.0,
        alignment: Alignment.centerRight,
      ),
      title: Text(post.title, textAlign: TextAlign.left),
      onTap: () => Navigator.of(context).push(
        MaterialPageRoute(builder: (context) => articel(post: post)),
      ),
      trailing: _Post(post: post),
    );
  }
}

class _Post extends StatefulWidget {
  final PostModel post;

  const _Post({
    Key key,
    @required this.post,
  })  : assert(post != null),
        super(key: key);

  @override
  PostState createState() => new PostState(
        post: post,
      );
}

class PostState extends State<_Post> {
  final PostModel post;

  PostState({Key key, @required this.post})
      : assert(post != null),
        super();

  static Future<bool> _liked = test();

  static Future<bool> test() async{
    final directory = await getApplicationDocumentsDirectory();
    return false;
  }
  static bool liked = false;

  _pressed() async {
    if (liked == true) {
      setState(() {
        liked = false;
      });
      IsLiked.deleteLike(post.postId);
    } else {
      liked = true;
      IsLiked.like(post);
      setState(() {
        liked = true;
      });
    }
    final directory = await getApplicationDocumentsDirectory();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _liked,
      builder: (BuildContext context, AsyncSnapshot<bool> snapshot){
        if(snapshot.hasData){
          return IconButton(
            icon: new Icon(liked ? Icons.favorite : Icons.favorite_border,
                color: liked ? Colors.red : Colors.grey, size: 30),
            onPressed: () => _pressed(),
          );
        }else{
          return CircularProgressIndicator(
            backgroundColor: Hexcolor("#FFFFFF"),
            valueColor: new AlwaysStoppedAnimation<Color>(Hexcolor('#FE2E2E')));
        }
      },
    );

  }
}


【问题讨论】:

    标签: flutter dart button async-await future


    【解决方案1】:

    好吧,我终于找到了解决方案。它与未来的构建者一起工作,我不得不在里面用liked = snapshot.data 初始化喜欢

    最后的类是这样的:

    class PostState extends State<_Post> {
      final PostModel post;
    
      PostState({Key key, @required this.post})
          : assert(post != null),
            super();
    
      static Future<bool> _liked = test();
    
      static Future<bool> test() async{
        final directory = await getApplicationDocumentsDirectory();
        return false;
      }
      static bool liked;
    
      _pressed() async {
    
        if (liked == true) {
          setState(() {
            liked = false;
          });
          IsLiked.deleteLike(post.postId);
        } else {
          liked = true;
          IsLiked.like(post);
          setState(() {
            liked = true;
          });
        }
        final directory = await getApplicationDocumentsDirectory();
      }
    
      @override
      Widget build(BuildContext context) {
        return FutureBuilder(
          future: _liked,
          builder: (BuildContext context, AsyncSnapshot<bool> snapshot){
            if(snapshot.hasData){
              liked = snapshot.data;
              return IconButton(
                icon: new Icon(liked ? Icons.favorite : Icons.favorite_border,
                    color: liked ? Colors.red : Colors.grey, size: 30),
                onPressed: () => _pressed(),
              );
            }else{
              return CircularProgressIndicator(
                backgroundColor: Hexcolor("#FFFFFF"),
                valueColor: new AlwaysStoppedAnimation<Color>(Hexcolor('#FE2E2E')));
            }
          },
        );
    
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多