从另一个回来后重新绘制小部件

问题描述

我有一个MainExerseClass飞镖类。其中有ImageSequenceAnimator和LinearPercentIndicator,当控件通过弹出另一个类进入MainExerseClass飞镖时,应重新启动。 count1正在更新,但是ImageSequenceAnimator没有更新。 下面是代码

 class MainExerseClass extends StatefulWidget {
    
    
    
    
      @override
      State<StatefulWidget> createState() {
        // Todo: implement createState
        return Exersise();
    
      }
    }
    
    class Exersise extends State<MainExerseClass> with WidgetsBindingObserver{
      var count1;
      @override
      void didChangeAppLifecycleState(AppLifecycleState state) {
        if (state == AppLifecycleState.resumed) {
          //do your stuff
          _requestsqlData();
        }
      }
      @override
      void dispose() {
        WidgetsBinding.instance.removeObserver(this);
        super.dispose();
      }
    
      @override
      void initState() {
        // Todo: implement initState
        //count1 = widget.progress;
        _requestsqlData();
    
        super.initState();
      }
    
    
    
      void _requestsqlData() {
        _requestsqlDataAsync();
      }
    
      void _requestsqlDataAsync() async {
        int i = await DatabaseHelper.instance.getDayExcCounter("Day 1");
        setState(() {
          count1 = i;
        });
    
        print(count1);
      }
      void _gotoB() async {
    
        String parameter = await Navigator.push(
          context,MaterialPageRoute(builder: (context) => Resttimer(ExcerciselistPojo.randomList[count1].name,count1.toString())),);
    
        setState(() {
          count1 = int.tryParse(parameter);
        });
      }
    
      @override
      Widget build(BuildContext context) {
        // Todo: implement build
        SizeConfig().init(context);
        return Scaffold(
            body: new Column(
          children: <Widget>[
            new Row(
              children: <Widget>[
                Builder(
                  builder: (context) => IconButton(
                    icon: Icon(Icons.arrow_back),iconSize: 30,onpressed: () {
                      // Here i want context
                      if (Navigator.canPop(context)) {
                        Navigator.pop(context);
                      } else {
                        SystemNavigator.pop();
                      }
                    },),new Container(
                    margin: const EdgeInsets.fromLTRB(20,0),child: new Text("Exercise",style: new TextStyle(
                            color: Colors.black,fontSize: 25,fontWeight: FontWeight.bold)))
              ],new Container(
                margin: const EdgeInsets.fromLTRB(0,10,child: IntervalProgressBar(
                    direction: IntervalProgressDirection.horizontal,max: ExcerciselistPojo.randomList.length,progress: count1,intervalSize: 2,size: Size(600,10),highlightColor: Colors.pink,defaultColor: Colors.grey,intervalColor: Colors.transparent,intervalHighlightColor: Colors.transparent,reverse: false,radius: 0)),new Container(
              margin: EdgeInsets.fromLTRB(0,5,child: new Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,children: <Widget>[
                  new Container(
                    height: 30,alignment: Alignment.centerLeft,child: FlatButton(
    
                      child: Image.asset("assets/images/play.webp"),onpressed: () async {
                        //_updatecountertodb();
                        count1--;
                        if(count1<0)
                          count1=0;
                        await DatabaseHelper.instance.insertExcCounter("Day 1",count1);
                        _gotoB();
                      },new Container(
                    height: 30,alignment: Alignment.centerRight,onpressed: () async {
                        //_updatecountertodb();
                        count1++;
                        if(count1>5)
                          count1=0;
                        await DatabaseHelper.instance.insertExcCounter("Day 1",)
                ],child: new ImageSequenceAnimator(
                "assets/images/" + ExcerciselistPojo.randomList[count1].imageUrl,"Pic_","webp",3,isAutoplay: true,color: null,fps: 2,isLooping: true,height: 300,child: IconButton(
                icon: Image.asset("assets/images/rest_time_exc.png"),onpressed: () {},new Container(
              margin: EdgeInsets.fromLTRB(10,SizeConfig.screenHeight /16,child: new Text(ExcerciselistPojo.randomList[count1].name,style: new TextStyle(
                      fontSize: 25,fontWeight: FontWeight.bold,color: Colors.blueGrey)),SizeConfig.screenHeight /44,child: new LinearPercentIndicator(
                animation: true,animationDuration: 6000,lineHeight: SizeConfig.screenHeight / 10,percent: 1,center: Text("100/68%"),linearstrokeCap: LinearstrokeCap.butt,progressColor: Colors.pink,)
          ],));
    
    
      }
    
    
    }

我正在通过使用第二种类导航到MainExerseClass dart

 onTap: () {
                            Navigator.pop(context,count);
                          },
MainExerseClass中的

计数正在更新,但是ImageSequenceAnimator没有刷新,它显示的是旧动画。而且我想重新启动LinearPercentIndicator。

解决方法

我相信您可以通过将UniqueKey传递给要再次呈现的小部件来解决您的问题,如下所示:

Widget(key: uniqueKey(),...)
,

您可以在下面复制粘贴运行完整代码
为了使下面的演示工作正常进行,您需要将png文件从 https://github.com/aliyigitbireroglu/flutter-image-sequence-animator/tree/master/image_sequence_animator/example/assets/ImageSequence

assets:
  - assets/ImageSequence/

您不需要使用"assets/images/" + ExcerciselistPojo.randomList[count1].imageUrl
您可以直接使用imageSequenceAnimator.skip(count1.toDouble())

代码段

  ImageSequenceAnimatorState imageSequenceAnimator;

  void onReadyToPlay(ImageSequenceAnimatorState _imageSequenceAnimator) {
    imageSequenceAnimator = _imageSequenceAnimator;
  }

  void onPlaying(ImageSequenceAnimatorState _imageSequenceAnimator) {
    setState(() {});
  }

  void _gotoB() async {
    String parameter = await Navigator.push(
      context,MaterialPageRoute(builder: (context) => RouteB()),);

    setState(() {
      count1 = int.tryParse(parameter);
      imageSequenceAnimator.skip(count1.toDouble());
    });
  }

工作演示

enter image description here

完整代码

import 'package:flutter/material.dart';
import 'package:intervalprogressbar/intervalprogressbar.dart';
import 'package:image_sequence_animator/image_sequence_animator.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',theme: ThemeData(
        primarySwatch: Colors.blue,visualDensity: VisualDensity.adaptivePlatformDensity,),home: MyHomePage(title: 'Flutter Demo Home Page'),);
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key,this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int count = 30;
  int count1 = 3;

  ImageSequenceAnimatorState imageSequenceAnimator;

  void onReadyToPlay(ImageSequenceAnimatorState _imageSequenceAnimator) {
    imageSequenceAnimator = _imageSequenceAnimator;
  }

  void onPlaying(ImageSequenceAnimatorState _imageSequenceAnimator) {
    setState(() {});
  }

  void _gotoB() async {
    String parameter = await Navigator.push(
      context,);

    setState(() {
      count1 = int.tryParse(parameter);
      imageSequenceAnimator.skip(count1.toDouble());
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[
            Expanded(
              flex: 4,child: Padding(
                padding: EdgeInsets.all(25),child: ImageSequenceAnimator(
                  "assets/ImageSequence","Frame_",5,"png",60,isAutoPlay: false,color: Colors.blue,onReadyToPlay: onReadyToPlay,onPlaying: onPlaying,Expanded(
              flex: 2,child: Container(
                  margin: const EdgeInsets.fromLTRB(0,10,0),child: IntervalProgressBar(
                      direction: IntervalProgressDirection.horizontal,max: count,progress: count1,intervalSize: 2,size: Size(600,10),highlightColor: Colors.pink,defaultColor: Colors.grey,intervalColor: Colors.transparent,intervalHighlightColor: Colors.transparent,reverse: false,radius: 0)),],floatingActionButton: FloatingActionButton(
        onPressed: _gotoB,tooltip: 'Increment',child: Icon(Icons.add),);
  }
}

class RouteB extends StatefulWidget {
  @override
  _RouteBState createState() => _RouteBState();
}

class _RouteBState extends State<RouteB> {
  TextEditingController _textEditingController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
          body: Column(
        children: [
          TextField(
            controller: _textEditingController,RaisedButton(
            child: Text('Go back'),onPressed: () {
              Navigator.pop(context,_textEditingController.text);
            },)),);
  }
}