首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在颤振中从其他StatefulWidget更新StatefulWidget的状态?

在颤振中从其他StatefulWidget更新StatefulWidget的状态?
EN

Stack Overflow用户
提问于 2022-11-10 07:46:50
回答 2查看 22关注 0票数 0

我正在尝试更新中间区域的动画开关的状态。我正试图在较低的区域使用setstate来实现这一点。但不起作用。

  1. 我做的第一件事是在主类中创建一个具有布尔数据类型的变量。
  2. 然后将这个变量传递给中间区域和较低区域的
  3. 。这个想法是,如果同一个变量被传递给我试图更新的类,以及具有set状态的类,它就会工作。但看来我错了。我希望得到一些帮助。我正在尝试的布尔变量是_rep变量

这是Home小部件

代码语言:javascript
复制
class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
  late AnimationController _animationController;
  late AnimationController _controller;
  late Animation<Offset> _animation;
  late Animation<Offset> _anime;
    bool _rep = true;
  @override
  void initState() {
    _animationController = AnimationController(
        vsync: this,
        duration: Duration(seconds: 2)
    );
    _animation = Tween<Offset>(
      begin:Offset (0.0, 0.0),
      end: Offset (0.0,3.0),
    ).animate(CurvedAnimation(
        parent: _animationController,
        curve: Curves.easeIn));

    _anime = Tween<Offset>(
      begin:Offset (0.0, 0.0),
      end: Offset (0.0,-0.55),
    ).animate(CurvedAnimation(
        parent: _animationController,
        curve: Curves.easeIn));

    super.initState();

  }

  @override
  void dispose() {
    _animationController.dispose();
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        scrollDirection: Axis.vertical,
         physics: const NeverScrollableScrollPhysics(),
        child: Padding(
          padding:  EdgeInsets.only(top: 3.h),
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                   TopIcon(icons: Icons.arrow_back, color:Colors.grey.shade300 ,),
                  SizedBox(
                    height: 13.h,
                      width: 13.w,
                      child: Image.asset('assets/images/download.png')
                  ),
                  TopIcon(icons: Icons.shopping_bag_outlined, color: Colors.grey.shade300,),
                ],
              ),
               SizedBox(
                height: 3.h,
              ),
               Text('Frappuccino',
                style: TextStyle(
                  fontSize: 27.sp,
                  fontWeight: FontWeight.bold
                ),
              ),
               Padding(
                 padding: const EdgeInsets.all(8.0),
                 child: Text('White Chocolate',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: Colors.grey.shade400
                  ),
              ),
               ),
              MiddleArea(
                     controller: _animationController,
                     animation: _animation,
                     rep: _rep,


              ),



               LowerArea(controller: _animationController, anime: _anime, rep = _rep),
            ],
          ),
        ),
      ),
    );
  }
}

这是中部地区

代码语言:javascript
复制
class MiddleArea extends StatefulWidget {
   MiddleArea({Key? key, required this.controller, required this.animation, required this.rep}) : super(key: key);
  AnimationController controller;
  Animation<Offset> animation;
  final bool rep;


  @override
  State<MiddleArea> createState() => _MiddleAreaState();
}

class _MiddleAreaState extends State<MiddleArea> {
  bool _flag = true;
  bool _favourite = true;

  @override
  Widget build(BuildContext context) {
    print(widget.rep);
    return SizedBox(
      height: 52.h,
      child: Stack(
        children: [
          Column(
              children: [
                Padding(
                  padding: const EdgeInsets.only(top: 135.0),
                  child: Text('STARBUCKS',
                    style: TextStyle(
                        fontFamily: 'Typette',
                        color: Colors.brown.shade200,
                        fontSize: 30.sp,
                        fontWeight: FontWeight.w400
                    ),
                  ),
                ),
                Text('STARBUCKS',
                  style: TextStyle(
                      fontFamily: 'Typette',
                      color: Colors.brown.shade100,
                      fontSize: 30.sp,
                      fontWeight: FontWeight.w400
                  ),
                ),
                Text('STARBUCKS',
                  style: TextStyle(
                      fontFamily: 'Typette',
                      color: Colors.brown.shade50,
                      fontSize: 30.sp,
                      fontWeight: FontWeight.w400
                  ),
                ),
              ],
            ),

          Column(
            children: [
              Row(
                 mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: const [
                  SizeAndFave(text: 'Preference'),
                  SizeAndFave(text: 'Fave!')
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  GestureDetector(
                    onTap: (){
                      setState(() {
                         _flag = !_flag;
                      });
                    },
                      child: AnimatedSwitcher(
                        duration: const Duration(milliseconds: 500),
                        transitionBuilder: (Widget child, Animation<double> animation){
                          return FadeTransition(opacity: animation, child: child,);
                        },
                        child: widget.rep == true?Padding(
                          padding: const EdgeInsets.all(14.0),
                          key: const Key('1'),
                          child: Container(
                              height: 40,
                              width: 40,
                              decoration: BoxDecoration(
                                  border: Border.all(
                                      color: Colors.brown.shade300,
                                      width: 3
                                  ),
                                  borderRadius: BorderRadius.circular(10)
                              ),
                              child: const Center(
                                child: Icon(
                                  Icons.coffee_outlined,
                                  size: 20,
                                ),
                              )
                          ),
                        ):null,
                      )
                  ),
                  GestureDetector(
                    onTap: (){
                      setState(() {
                        _favourite = !_favourite;
                      });
                    },
                      child: _favourite? TopIcon(icons: Icons.favorite_border, color: Colors.brown.shade300)
                      :TopIcon(
                          icons: Icons.favorite, color: Colors.brown.shade300)
                  )
                ],
              )
            ],
          ),
              AnimatedSwitcher(
                duration: Duration(seconds: 1),
                transitionBuilder: (Widget child, Animation<double> animation) {
                  return FadeTransition( opacity: animation,
                  child: child);
                },
                  child: _flag == true ? Center(
                    key: const Key('1'),
                    child: SlideTransition(
                      position: widget.animation,
                      child: SizedBox(
                        height: 80.h,
                        width: 80.w,
                         child: Image.asset('assets/images/starcup.png'),
                       ),
                    ),
                  ):Center(
                    key: const Key('2'),
                    child: SlideTransition(
                      position: widget.animation,
                      child: SizedBox(
                        height: 80.h,
                        width: 80.w,
                        child: Image.asset('assets/images/greeen.png'),
                      ),
                    ),
                  ),
                   ),
          Positioned(
              child:
          Align(
            alignment: Alignment.bottomRight,
            child: Padding(
              padding:  EdgeInsets.only(top: 30.h),
              child: TopIcon(
                  icons: Icons.car_crash_outlined, color: Colors.brown.shade300),
            ),
          )),

          const Positioned(
              child:
              Align(
                alignment: Alignment.bottomLeft,
                child: Padding(
                  padding: EdgeInsets.only(top: 330.0, left: 14),
                  child: Text('\$ 5.99',
                  style: TextStyle(
                    fontSize: 27,
                    fontWeight: FontWeight.bold
                  ),
                  ),
                ),
              ))
        ],
      ),
    );

  }
}

最后,下面的区域

代码语言:javascript
复制
class LowerArea extends StatefulWidget {
  final AnimationController controller;
  final Animation<Offset> anime;
  bool rep;




   LowerArea({Key? key, required this.controller, required this.anime, required this.rep}) : super(key: key);

  @override
  State<LowerArea> createState() => _LowerAreaState();
}

class _LowerAreaState extends State<LowerArea> {
  bool _bigger = true;
  bool _fade = true;

  void move(){

  }
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children:  [
              Padding(
                padding: EdgeInsets.all(1.h),
                child: const Text('Tall Frappuccino',
                  style: TextStyle(
                    fontWeight: FontWeight.w500
                  ),
                ),
              ),
              Padding(
                padding: EdgeInsets.only(right: 5.h),
                child: const Text('Swipe Down',
                  style: TextStyle(
                      fontWeight: FontWeight.w500
                  ),
                ),
              ),
              Padding(
                padding: EdgeInsets.all(2.h),
                child: const Text('Pickup',
                  style: TextStyle(
                      fontWeight: FontWeight.w500
                  ),
                ),
              )
            ],
          ),
        ),
        SlideTransition(
          position: widget.anime,

          child: AnimatedContainer(
            // height: 11.h,
            width: _bigger ? 35.h: 80.h,
            duration: const Duration(milliseconds: 500),
            child: Stack(
              fit: StackFit.loose,
              children: [
                Center(child: Image.asset('assets/images/baggie.png')),
                Center(
                  child: Padding(
                    padding:  EdgeInsets.only(bottom: 4.h),
                    child: GestureDetector(
                      onTap: (){
                           widget.controller.forward();
                           setState(() {
                             _bigger = !_bigger;
                             _fade = !_fade;
                             widget.rep = !widget.rep;

                             print('this is fade $_fade ');

                           });
                      },
                      child: AnimatedSwitcher(
                        duration: Duration(milliseconds: 300),
                        transitionBuilder: (Widget child, Animation<double> animation){
                          return FadeTransition(opacity: animation, child: child,);
                        },
                        child: _fade? Container(
                          key: Key('1'),
                          height: 8.h,
                          width: 7.w,
                          decoration: BoxDecoration(
                            color: Colors.black,
                            borderRadius: BorderRadius.circular(15)
                          ),
                          child: Column(
                            children:  [
                              Padding(
                                padding: EdgeInsets.all(0.3.h),
                                child: Icon(
                                  Icons.lock_outline,
                                  color: Colors.white54,
                                  size: 2.5.h,

                                ),
                              ),
                              Icon(
                                Icons.arrow_drop_down,
                                color: Colors.white12,
                                size: 3.h,
                              ),



                            ],
                          ),
                        ):null,
                      ),
                    ),
                  ),
                )
              ],
            ),
          ),
        )
      ],
    );

  }
EN

回答 2

Stack Overflow用户

发布于 2022-11-10 07:58:26

使用provider pacakges https://pub.dev/packages/provider

创建一个继承ChangeNotifyer函数的类,以创建要控制的标志和创建一个setter。

提供程序类

代码语言:javascript
复制
class StateController extends ChangeNotifier{
   bool _req = false;
   bool get req => _req; //getter
  
   setReqValue(){
      _req = !_req;
      notifyListener(); 
   }
}

main函数中声明提供程序类。您可以根据Wiget tree更改声明的位置,但首先在main中声明它

Change main.dart

代码语言:javascript
复制
void main(){
  runApp(
    Multiprovider(
      providers: [
         ChangeNotifierProvider(create: (_) => StateController()),
      ],
      child: HomePage(),
    )
  );
}

UI由notifyListener()更新。

变更UI

代码语言:javascript
复制
child: context.watch<StateController>().req == true ? Padding(
                          padding: const EdgeInsets.all(14.0),
                          key: const Key('1'),
                          child: Container(
                              height: 40,
                              width: 40,
                              decoration: BoxDecoration(
                                  border: Border.all(
                                      color: Colors.brown.shade300,
                                      width: 3
                                  ),
                                  borderRadius: BorderRadius.circular(10)
                              ),
                              child: const Center(
                                child: Icon(
                                  Icons.coffee_outlined,
                                  size: 20,
                                ),
                              )
                          ),
                        ):null,

变更状态

代码语言:javascript
复制
onTap: (){
                           widget.controller.forward();
                           setState(() {
                             _bigger = !_bigger;
                             _fade = !_fade;
                             context.read<StateController>().setReqValue();

                             print('this is fade $_fade ');

                           });
                      },
票数 0
EN

Stack Overflow用户

发布于 2022-11-10 08:00:36

我懒得试着理解你的代码。但是,如果您想在从导航到页面弹出后更新页面的状态。

在要更新的页面中

代码语言:javascript
复制
Navigation.push(context, /* Page that will change something */)
  // Future will trigger then you return to this page.
  .then((_) => setState(() {}))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74385643

复制
相关文章

相似问题

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