首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >(颤振)如何调用另一个类的setState方法?

(颤振)如何调用另一个类的setState方法?
EN

Stack Overflow用户
提问于 2022-11-08 07:02:34
回答 1查看 45关注 0票数 0

我想从另一个类调用方法,我使用了这种方法,但是方法没有正确地调用。`

代码语言:javascript
复制
        class PostModel extends StatefulWidget {
          final profilename;
          final bool isVideoUrl;
          final int urlsource;
          final videoUrl;
          const PostModel(
              {this.profilename,
              required this.isVideoUrl,
              required this.urlsource,
              this.videoUrl});
        
          @override
          State<PostModel> createState() => _PostModelState();
        }
        
        class _PostModelState extends State<PostModel> {
          @override
          Widget build(BuildContext context) {
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                NameSection(),
                InkWell(
                  onDoubleTap: , // **toggleLike()** Want to call from here 
                  child: (widget.isVideoUrl)
                      ? SizedBox(
                          width: MediaQuery.of(context).size.width,
                          height: MediaQuery.of(context).size.width,
                          child: VideoController(videosUrl[widget.urlsource % 6]))
                      : Image(
                          image: NetworkImage(
                              "https://picsum.photos/seed/${widget.urlsource}/400/400"),
                          width: MediaQuery.of(context).size.width,
                          fit: BoxFit.cover,
                        ),
                ),
                PostIcons(), // here is the widget .
                Padding(
                    padding: EdgeInsets.symmetric(horizontal: 10),
                    child:
                        Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                      SizedBox(
                        height: 5,
                      ),
                      Text(
                        "11,536 likes",
                        style: GoogleFonts.roboto(
                            color: Colors.white,
                            fontSize: 12,
                            fontWeight: FontWeight.bold),
                      ),
                      SizedBox(
                        height: 5,
                      ),
                      Text(
                        "akashbanerjee ‍♀️",
                        style: GoogleFonts.roboto(
                            color: Colors.white,
                            fontSize: 12,
                            fontWeight: FontWeight.bold),
                      ),
                      SizedBox(
                        height: 5,
                      ),
                      Text(
                        "View all 244 comments ",
                        style: GoogleFonts.roboto(
                            color: Color.fromARGB(255, 186, 186, 186), fontSize: 12),
                      ),
                      SizedBox(
                        height: 5,
                      ),
                      Text(
                        "5 hours ago",
                        style: GoogleFonts.roboto(
                            color: Color.fromARGB(255, 186, 186, 186), fontSize: 10),
                      ),
                      SizedBox(
                        height: 10,
                      ),
                      Divider(
                        color: Color.fromARGB(255, 77, 77, 77),
                        indent: 0,
                        endIndent: 0,
                      )
                    ]))
              ],
            );
          }
        }
    
    ```
    ```
    
        class PostIcons extends StatefulWidget {
          const PostIcons({Key? key}) : super(key: key);
        
          @override
          State<PostIcons> createState() => PostIconsState();
        }
    
        class PostIconsState extends State<PostIcons> {
          bool liked = false;
        
          toggleLike() { // i want to call this function from above class.
            setState(() {
              liked = !liked;
            });
          }
        
          bool saved = false;
          toggleSavePost() {
            setState(() {
              saved = !saved;
              ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                content: (saved) ? Text("Post saved") : Text("Post unsaved"),
                duration: Duration(milliseconds: 1000),
              ));
            });
          }
        
          showShareBottomModal() {
            // setState(() {
            showModalBottomSheet<void>(
                // context and builder are
                // required properties in this widget
                backgroundColor: Color.fromARGB(255, 38, 38, 38),
                shape: const RoundedRectangleBorder(
                  borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(24), topRight: Radius.circular(24)),
                ),
                context: context,
                builder: (BuildContext context) {
                  // we set up a container inside which
                  // we create center column and display text
                  // Returning SizedBox instead of a Container
                  return SharePost();
                });
            // });
          }
        
          @override
          Widget build(BuildContext context) {
            return Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    IconButton(
                        onPressed: toggleLike,
                        iconSize: 28,
                        icon: Icon(
                          liked ? Icons.favorite : Icons.favorite_outline,
                          color: liked ? Colors.red : Colors.white,
                        )),
                    // SizedBox(
                    //   width: 0,
                    // ),
                    Transform(
                      alignment: Alignment.center,
                      transform: Matrix4.rotationY(math.pi),
                      child: IconButton(
                          iconSize: 28,
                          onPressed: null,
                          icon: Icon(
                            FeatherIcons.messageCircle,
                            color: Colors.white,
                          )),
                    ),
                    IconButton(
                        onPressed: showShareBottomModal,
                        iconSize: 28,
                        icon: Icon(
                          FeatherIcons.send,
                          color: Colors.white,
                        )),
                  ],
                ),
                IconButton(
                  onPressed: toggleSavePost,
                  iconSize: 28,
                  icon: Icon(saved ? Icons.bookmark : Icons.bookmark_border_outlined),
                  color: Colors.white,
                )
              ],
            );
          }
        }

PostModel类

代码语言:javascript
复制
class Feeds extends StatefulWidget {
 

  @override
  State<Feeds> createState() => _FeedsState();
}

class _FeedsState extends State<Feeds> {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: List.generate(storyList.length, (index) {
        return PostModel(isVideoUrl: false, urlsource: index);
      }),
    );
  }
}

Postmodel小部件在另一个类的列表中。

因此,有人能建议我一些很好的实用方法来调用其他类的setState (不是孩子,也不是家长,完全不同的类)。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-11-08 07:58:33

当您使用这样的GlobalKey时,还需要将该键提供给您试图用它控制的小部件。所以在你的情况下

代码语言:javascript
复制
PostIcons(key: globalKey)

下面是一个小部件使用这样的键控制另一个小部件的最小工作示例:

代码语言:javascript
复制
import 'package:flutter/material.dart';

void main() => runApp(const MyApp());
final GlobalKey<AState> globalKey = GlobalKey();

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            body: Center(
                child: Column(children: [
      A(key: globalKey),
      TextButton(
          onPressed: () {
            globalKey.currentState?.increaseI();
          },
          child: Text("click"))
    ]))));
  }
}

class A extends StatefulWidget {
  const A({Key? key}) : super(key: key);

  @override
  State<A> createState() => AState();
}

class AState extends State<A> {
  int i = 1;

  void increaseI() {
    setState(() {
      i++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Text(i.toString());
  }
}

编辑:

因此,对于您的代码,尝试添加

代码语言:javascript
复制
final GlobalKey<PostIconsState> globalKey = GlobalKey();

在你的_PostModelState里面。所以就在下面

代码语言:javascript
复制
    class _PostModelState extends State<PostModel> {

然后这一行:

代码语言:javascript
复制
            PostIcons(), // here is the widget .

你换到

代码语言:javascript
复制
            PostIcons(key: globalKey), // here is the widget .

然后你就可以改变

代码语言:javascript
复制
              onDoubleTap: , // **toggleLike()** Want to call from here 

代码语言:javascript
复制
              onDoubleTap: () => globalKey.currentState?.toggleLike(),

我认为您之前遇到的问题是globalKey是在类之外定义的。通过在类中定义它,可以确保每个实例都有不同的键。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74356788

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档