您如何在Flutter中显示一堆相同的小部件?

时间:2019-09-16 01:53:03

标签: flutter dart flutter-layout

我已经创建了一个GameBoard小部件,我想用我也创建的16个GameTile小部件来填充。出于游戏目的,GameTile小部件正在使用Positioned小部件。如何生成16个图块而不必逐个键入?

这是我的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,
          ),
        ),
      ),
    ),
  ),
);

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

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

功能显示它

代码段

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.
    );
  }
}

演示,小部件2位于小部件1顶部

enter image description here