【问题标题】:Is it possible to use Flame's game widget beside flutter's widgets?是否可以在 Flutter 的小部件旁边使用 Flame 的游戏小部件?
【发布时间】:2022-01-11 18:20:32
【问题描述】:

简而言之,由于火焰游戏本身就是一个小部件,我想将该小部件添加到列小部件中。当我将它添加到 runApp() 时游戏运行,但在列中添加小部件时它没有。为什么?

import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Sprite examples')),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                'This a sample text!',
                style: TextStyle(fontSize: 22),
              ),
              GameWidget(game: SpriteSample())       //<========== game widget
            ],
          ),
        ),
      ),
    );
  }
}

class SpriteSample extends FlameGame {
  @override
  Future<void>? onLoad() {
    add(SpriteOne());
    return super.onLoad();
  }
}

class SpriteOne extends PositionComponent {
  final Paint _paint = Paint()..color = Colors.red;

  @override
  Future<void>? onLoad() {
    return super.onLoad();
  }

  @override
  void render(Canvas canvas) {
    canvas.drawCircle(Offset(150, 150), 25, _paint);
  }

  @override
  void update(double dt) {
    super.update(dt);
  }
}

【问题讨论】:

    标签: flutter flame


    【解决方案1】:

    您需要将其包装在 Expanded 小部件(或另一个为其指定大小的小部件,例如 SizedBox)中,否则由于无限大小的限制,GameWidget 将无法布局:

    class _MyAppState extends State<MyApp> {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(title: Text('Sprite examples')),
            body: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    'This a sample text!',
                    style: TextStyle(fontSize: 22),
                  ),
                  Expanded(
                    child: GameWidget(game: SpriteSample()),
                  )
                ],
              ),
            ),
          ),
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-10-21
      • 1970-01-01
      • 2018-08-24
      • 2021-08-15
      • 2021-07-10
      • 2018-04-28
      • 2018-06-27
      • 1970-01-01
      • 2022-10-24
      相关资源
      最近更新 更多