Search code examples
flutterdartcenteringflame

Center an incrementing number using the "setByPostion" component in Flutter


I am developing a new game and ran into an issue where when my score increases to more than 10 or by another decimal it will not center properly due to only the first decimal in the number being in the center of the screen.

import 'package:flame/components/text_component.dart';
import 'package:flame/game.dart';
import 'package:flame/position.dart';
import 'package:flame/text_config.dart';
import 'package:flutter/material.dart';

class Test extends BaseGame{

  TextComponent _scoreText;
  int score;
  TextComponent _text;

  Test() {
    // SCORE TEXT
    score = 0;
    _scoreText = TextComponent(score.toString(),
        config: TextConfig(
            color: Colors.white, fontFamily: 'Audiowide', fontSize: 70));
    add(_scoreText);
  }


  void resize(Size size) {
    super.resize(size);
    _scoreText.setByPosition(Position(
        (size.width / 2) - (_scoreText.width / 2), (size.height / 10)));
  }
  
}

Solution

  • I fixed this problem by using the anchor widget, making its origin the center of the text box and not the top left.

      void resize(Size size) {
        super.resize(size);
        _scoreText.setByPosition(Position(
        _scoreText.anchor = Anchor.center;
            (size.width / 2), (size.height / 10)));
      }