flutter - 如何在 Flutter 中显示一堆相同的 widget?

标签 flutter dart flutter-layout

我创建了一个 GameBoard 小部件,我想用我也创建的 16 个 GameTile 小部件填充它。出于游戏目的,GameTile 小部件正在使用 Positioned 小部件。如何生成 16 个图 block 而无需逐个输入?

这是我的 GameBoard 小部件代码:

return Container(
  width: _myScreenWidth * 0.80,
  height: _myScreenWidth * 0.80,
  child: Stack(
    children: [
      List.generate(16, (index) {
        return GameTile(value: tileValue[index], color: tileColor[index], x: tileXCoordinate[index], y: tileYCoordinate[index]);
      }),
    ],
  ),
);

这是我的 GameTile 代码:

return Positioned(
  left: x,
  bottom: y,
  child: PhysicalModel(
    borderRadius: BorderRadius.circular(10.0),
    color: color,
    child: Container(
      width: _tileWidth,
      height: _tileHeight,
      child: Center(
        child: Text(
          value.toString(),
          textAlign: TextAlign.center,
          style: new TextStyle(
            fontSize: _myScreenWidth * 0.07,
            color: backgroundColor,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    ),
  ),
);

非常感谢任何帮助。

最佳答案

使用函数和列表来存储生成的小部件
并用函数

显示

代码片段

List<Widget> getList() {
    List<Widget> widgeList = [];
    for (var i = 0; i < 10; i++) {
      for (var item in widget.items) {
        widgeList.add(Positioned(
          left: item.x,
          bottom: item.y,
          child: PhysicalModel(
            borderRadius: BorderRadius.circular(10.0),
            color: Colors.blueAccent,
            child: Container(
              width: item.tileWidth,
              height: item.tileHeight,
              child: Center(
                child: Text(
                  item.value,
                  textAlign: TextAlign.center,
                  style: new TextStyle(
                    //fontSize: _myScreenWidth * 0.07,
                    //color: backgroundColor,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
          ),
        ));
      }
    }
    return widgeList;
  }
...

body: Stack(
    children: getList(),
  ),

你的游戏类看起来像这样,它只是一个演示我没有重新创建你的所有属性

class Game {
  double x;
  double y;
  double tileWidth;
  double tileHeight;
  String value;

  Game({
    this.x,
    this.y,
    this.tileWidth,
    this.tileHeight,
    this.value,
  });

  factory Game.fromJson(Map<String, dynamic> json) => Game(
        x: json["x"],
        y: json["y"],
        tileWidth: json["tileWidth"],
        tileHeight: json["tileHeight"],
        value: json["value"],
      );

  Map<String, dynamic> toJson() => {
        "x": x,
        "y": y,
        "tileWidth": tileWidth,
        "tileHeight": tileHeight,
        "value": value,
      };
}

完整代码

import 'package:flutter/material.dart';
import 'dart:convert';

void main() => runApp(MyApp());

List<Game> gameFromJson(String str) =>
    List<Game>.from(json.decode(str).map((x) => Game.fromJson(x)));

String gameToJson(List<Game> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Game {
  double x;
  double y;
  double tileWidth;
  double tileHeight;
  String value;

  Game({
    this.x,
    this.y,
    this.tileWidth,
    this.tileHeight,
    this.value,
  });

  factory Game.fromJson(Map<String, dynamic> json) => Game(
        x: json["x"],
        y: json["y"],
        tileWidth: json["tileWidth"],
        tileHeight: json["tileHeight"],
        value: json["value"],
      );

  Map<String, dynamic> toJson() => {
        "x": x,
        "y": y,
        "tileWidth": tileWidth,
        "tileHeight": tileHeight,
        "value": value,
      };
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;
  static String data =
      '[ {"x" : 1.0,    "y" : 2.0, "tileWidth" : 100.0,  "tileHeight" : 200.0, "value" : "test"}, {"x" : 10.0, "y" : 20.0, "tileWidth" : 100.0,   "tileHeight" : 200.0, "value" : "test 2"} ] ';
  List<Game> items = gameFromJson(data);
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }


  List<Widget> getList() {
    List<Widget> widgeList = [];
    for (var i = 0; i < 10; i++) {
      for (var item in widget.items) {
        widgeList.add(Positioned(
          left: item.x,
          bottom: item.y,
          child: PhysicalModel(
            borderRadius: BorderRadius.circular(10.0),
            color: Colors.blueAccent,
            child: Container(
              width: item.tileWidth,
              height: item.tileHeight,
              child: Center(
                child: Text(
                  item.value,
                  textAlign: TextAlign.center,
                  style: new TextStyle(
                    //fontSize: _myScreenWidth * 0.07,
                    //color: backgroundColor,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
          ),
        ));
      }
    }
    return widgeList;
  }

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

  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Stack(
        children: getList(),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

演示,Widget 2 在 Widget 1 之上

enter image description here

关于flutter - 如何在 Flutter 中显示一堆相同的 widget?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57949533/

相关文章:

android - 将 Android 和 iOS 库导入 Flutter 项目

firebase - 如果不存在,则在 firestore 中创建集合( flutter )

flutter - 如何在 onPressed() 中动态更改按钮的背景颜色

android - Flutter程序未显示图像

登录屏幕背景的 Flutter video_player 带来黑屏

flutter - 在哪里放置一个函数来触发 flutter/dart 应用程序的退出/停止/关闭事件?

flutter - 如何在 Flutter 的 AlertDialog 中实现 Slider?

dart - 为什么 Flutter (dart) 处理图片这么慢?

json - 重定向循环检测到 Dart

android - 如何在 flutter 中创建 SharedPreferences 的单例类