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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<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}xu{00B3} + ${myController.text}xu{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;
}
}
</code>
<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}xu{00B3} + ${myController.text}xu{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; } } </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}xu{00B3} + ${myController.text}xu{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.

4

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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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}xu{00B3} + ${myController.text}xu{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;
}
}
</code>
<code>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}xu{00B3} + ${myController.text}xu{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; } } </code>
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}xu{00B3} + ${myController.text}xu{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;
  }
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật