Search code examples
flutterdartflutter-animation

Flutter - image from assets disappears during animation


I want to make an animation in my app where I load an image and make it move along a certain path. I have drawn a line made up of several points and firstly I tried to make a dot moving along - everything worked okay.

This is my code:

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Turtle Maths',
      theme: ThemeData(
        primarySwatch: Colors.green,
        visualDensity: VisualDensity.adaptivePlatformDensity,
        useMaterial3: false,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage>
    with SingleTickerProviderStateMixin {
  final myController = TextEditingController();
  int ratio = 10;
  double _progress = 0.0;
  late Animation<double> animation;
  late AnimationController controller;

  @override
  void initState() {
    super.initState();

    controller = AnimationController(
        duration: const Duration(milliseconds: 3000), vsync: this);

    animation = Tween(begin: 0.0, end: 1.0).animate(controller)
      ..addListener(() {
        setState(() {
          _progress = animation.value;
        });
      });

  }

  @override
  void dispose() {
    myController.dispose();
    super.dispose();
  }

  Future<ui.Image> _loadImage(String imagePath) async {
    ByteData bd = await rootBundle.load(imagePath);
    final Uint8List bytes = Uint8List.view(bd.buffer);
    final ui.Codec codec = await ui.instantiateImageCodec(bytes,
        targetHeight: 60, targetWidth: 60);
    final ui.Image image = (await codec.getNextFrame()).image;

    return image;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: const Text("Turtle Maths")),
        body: LayoutBuilder(
          builder: (BuildContext context, BoxConstraints constraints) {
            return Column(
              children: [
                AnimatedBuilder(
                  animation: controller,
                  builder: (BuildContext context, _) {
                    return TextField(
                      controller: myController,
                      keyboardType: TextInputType.number,
                      decoration: InputDecoration(
                          prefixIcon: const Icon(PiSymbol.pi_outline),
                          hintText: "Coefficient",
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                            borderSide: const BorderSide(
                              color: Colors.black,
                              width: 1,
                              style: BorderStyle.solid,
                            ),
                          ),
                          suffixIcon: Container(
                              margin: const EdgeInsets.all(8),
                              child: ElevatedButton(
                                  style: ElevatedButton.styleFrom(
                                    minimumSize: const Size(100, 50),
                                    iconColor: Colors.red,
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(30.0),
                                    ),
                                  ),
                                  onPressed: () {
                                    setState(() {
                                      if (myController.text.isNotEmpty) {
                                        ratio = int.parse(myController.text);
                                        controller.reset();
                                        controller.forward();
                                      }
                                    });
                                  },
                                  child: const Text("RUN")))),
                    );
                  },
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text(
                      "${myController.text}x\u{00B3} + ${myController.text}x\u{00B2} + ${myController.text}x + ${myController.text} = 0",
                      style: const TextStyle(fontSize: 18)),
                ),
                Expanded(          
                  child: FutureBuilder<ui.Image>(
                    future: _loadImage("assets/images/turtle.png"),
                    builder:(BuildContext context, AsyncSnapshot<ui.Image> snapshot){
                      if (snapshot.connectionState == ConnectionState.done){
                        return CustomPaint(
                        painter: MyPainter(constraints.maxWidth / 2,
                            constraints.maxHeight / 2, ratio, _progress, snapshot.data),
                        size: Size(constraints.maxWidth, constraints.maxHeight));
                      }
                      else{
                        return CustomPaint(
                        painter: MyPainter(constraints.maxWidth / 2,
                            constraints.maxHeight / 2, ratio, _progress),
                        size: Size(constraints.maxWidth, constraints.maxHeight));
                      }
                    }
                )),
              ],
            );
          },
        ));
  }
}

class MyPainter extends CustomPainter {
  ui.Image? image;
  double _width = 0;
  double _height = 0;
  int _ratio = 0;
  final double _progress;

  MyPainter(width, height, ratio, this._progress, [this.image]) {
    _width = width;
    _height = height;
    _ratio = ratio * 10;
  }

  @override
  void paint(Canvas canvas, Size size) async {
    Paint linePaint = Paint()
      ..strokeWidth = 20
      ..strokeCap = StrokeCap.butt
      ..style = PaintingStyle.stroke;

    var path = getPath();
    ui.PathMetrics pathMetrics = path.computeMetrics();
    ui.PathMetric pathMetric = pathMetrics.elementAt(0);
    final pos = pathMetric.getTangentForOffset(pathMetric.length * _progress);
    Path extracted = pathMetric.extractPath(0.0, pathMetric.length * _progress);

    linePaint.strokeWidth = 6;

    canvas.drawPath(extracted, linePaint);
    if (image == null) {
      canvas.drawCircle(pos!.position, linePaint.strokeWidth / 2, linePaint);
    } else {
      canvas.drawImage(image!, pos!.position, linePaint);
    }
  }

  Path getPath() {
    return Path()
      ..moveTo(_width, _height)
      ..lineTo(_width + _ratio, _height)
      ..lineTo(_width + _ratio, _height)
      ..lineTo(_width + _ratio, _height - _ratio)
      ..lineTo(_width - _ratio, _height - _ratio)
      ..lineTo(_width - _ratio, _height + _ratio);
  }

  @override
  bool shouldRepaint(covariant MyPainter oldDelegate) {
    return oldDelegate._progress != _progress;
  }
}

I had null-errors before so I made an if statement to check if image is there and now the image loads at the very beginning then I see the dot during an animation with image appearing again only at the very end.

Could somebody please explain what I am doing wrong here and what is the correct way? Thanks in advance.


Solution

  • The problem here is with future builder's future being built every frame.

    future: _loadImage("assets/images/turtle.png")

    Here, image is being loaded on everyframe.

    From official doc at https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html

    Managing the future The future must have been obtained earlier, e.g. during State.initState, State.didUpdateWidget, or State.didChangeDependencies. It must not be created during the State.build or StatelessWidget.build method call when constructing the FutureBuilder. If the future is created at the same time as the FutureBuilder, then every time the FutureBuilder's parent is rebuilt, the asynchronous task will be restarted.

    A general guideline is to assume that every build method could get called every frame, and to treat omitted calls as an optimization.

    So once replace this with some future which is created at init state, you get the image displayed.

    import 'dart:ui' as ui;
    
    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    
    void main() {
      runApp(const MyApp());
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Turtle Maths',
          theme: ThemeData(
            primarySwatch: Colors.green,
            visualDensity: VisualDensity.adaptivePlatformDensity,
            useMaterial3: false,
          ),
          home: const MyHomePage(),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      const MyHomePage({super.key});
    
      @override
      State<MyHomePage> createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage>
        with SingleTickerProviderStateMixin {
      final myController = TextEditingController();
      int ratio = 10;
      double _progress = 0.0;
      late Animation<double> animation;
      late AnimationController controller;
    
      late Future<ui.Image> _imageFuture; // added this
    
      @override
      void initState() {
        super.initState();
    
        controller = AnimationController(
            duration: const Duration(milliseconds: 3000), vsync: this);
    
        animation = Tween(begin: 0.0, end: 1.0).animate(controller)
          ..addListener(() {
            setState(() {
              _progress = animation.value;
            });
          });
    
        _imageFuture = _loadImage("assets/images/turtle.png"); // added this
      }
    
      @override
      void dispose() {
        myController.dispose();
        super.dispose();
      }
    
      Future<ui.Image> _loadImage(String imagePath) async {
        ByteData bd = await rootBundle.load(imagePath);
        final Uint8List bytes = Uint8List.view(bd.buffer);
        final ui.Codec codec = await ui.instantiateImageCodec(bytes,
            targetHeight: 60, targetWidth: 60);
        final ui.Image image = (await codec.getNextFrame()).image;
        return image;
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(title: const Text("Turtle Maths")),
            body: LayoutBuilder(
              builder: (BuildContext context, BoxConstraints constraints) {
                return Column(
                  children: [
                    AnimatedBuilder(
                      animation: controller,
                      builder: (BuildContext context, _) {
                        return TextField(
                          controller: myController,
                          keyboardType: TextInputType.number,
                          decoration: InputDecoration(
                              prefixIcon: const Icon(Icons.pie_chart),
                              hintText: "Coefficient",
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(10),
                                borderSide: const BorderSide(
                                  color: Colors.black,
                                  width: 1,
                                  style: BorderStyle.solid,
                                ),
                              ),
                              suffixIcon: Container(
                                  margin: const EdgeInsets.all(8),
                                  child: ElevatedButton(
                                      style: ElevatedButton.styleFrom(
                                        minimumSize: const Size(100, 50),
                                        iconColor: Colors.red,
                                        shape: RoundedRectangleBorder(
                                          borderRadius: BorderRadius.circular(30.0),
                                        ),
                                      ),
                                      onPressed: () {
                                        setState(() {
                                          if (myController.text.isNotEmpty) {
                                            ratio = int.parse(myController.text);
                                            controller.reset();
                                            controller.forward();
                                          }
                                        });
                                      },
                                      child: const Text("RUN")))),
                        );
                      },
                    ),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(
                          "${myController.text}x\u{00B3} + ${myController.text}x\u{00B2} + ${myController.text}x + ${myController.text} = 0",
                          style: const TextStyle(fontSize: 18)),
                    ),
                    Expanded(
                        child: FutureBuilder<ui.Image>(
                            future: _imageFuture,   //replaced this line
                            builder: (BuildContext context,
                                AsyncSnapshot<ui.Image> snapshot) {
                              if (snapshot.connectionState ==
                                  ConnectionState.done) {
                                return CustomPaint(
                                    painter: MyPainter(
                                        constraints.maxWidth / 2,
                                        constraints.maxHeight / 2,
                                        ratio,
                                        _progress,
                                        snapshot.data),
                                    willChange: true,
                                    size: Size(constraints.maxWidth,
                                        constraints.maxHeight));
                              } else {
                                return CustomPaint(
                                    painter: MyPainter(
                                        constraints.maxWidth / 2,
                                        constraints.maxHeight / 2,
                                        ratio,
                                        _progress),
                                    size: Size(constraints.maxWidth,
                                        constraints.maxHeight));
                              }
                            })),
                  ],
                );
              },
            ));
      }
    }
    
    class MyPainter extends CustomPainter {
      ui.Image? image;
      double _width = 0;
      double _height = 0;
      int _ratio = 0;
      final double _progress;
    
      MyPainter(width, height, ratio, this._progress, [this.image]) {
        _width = width;
        _height = height;
        _ratio = ratio * 10;
      }
    
      @override
      void paint(Canvas canvas, Size size) async {
        Paint linePaint = Paint()
          ..strokeWidth = 20
          ..strokeCap = StrokeCap.butt
          ..style = PaintingStyle.stroke;
    
        var path = getPath();
        ui.PathMetrics pathMetrics = path.computeMetrics();
        ui.PathMetric pathMetric = pathMetrics.elementAt(0);
        final pos = pathMetric.getTangentForOffset(pathMetric.length * _progress);
        Path extracted = pathMetric.extractPath(0.0, pathMetric.length * _progress);
    
        linePaint.strokeWidth = 6;
    
        canvas.drawPath(extracted, linePaint);
        if (image == null) {
          canvas.drawCircle(pos!.position, linePaint.strokeWidth / 2, linePaint);
        } else {
          canvas.drawImage(image!, pos!.position, linePaint);
        }
      }
    
      Path getPath() {
        return Path()
          ..moveTo(_width, _height)
          ..lineTo(_width + _ratio, _height)
          ..lineTo(_width + _ratio, _height)
          ..lineTo(_width + _ratio, _height - _ratio)
          ..lineTo(_width - _ratio, _height - _ratio)
          ..lineTo(_width - _ratio, _height + _ratio);
      }
    
      @override
      bool shouldRepaint(covariant MyPainter oldDelegate) {
        return oldDelegate._progress != _progress;
      }
    }