Coding Hotel
Coding Hotel

Reputation: 137

How to randomly position widgets in a layout

Lets say I want to randomly position the widgets in a specific layout, like in the image attached below, how could I achieve it?

The Image

I was thinking of using a wrap widget, but that did not quit work, because it is not randomizing the children in a line. My code until now

return Wrap(
   spacing: 30,
   children: [
        buildprofile(),
        buildprofile(),
        buildprofile(),
        buildprofile(),
      ],
    );

buildprofile() {
  return Column(
    children: [
      CircleAvatar(
        radius: 64,
        backgroundColor: Colors.pink,
        child: (CircleAvatar(
          radius: 62,
          backgroundImage: NetworkImage(profilepic),
        )),
      ),
      SizedBox(
        height: 10,
      ),
      Text(
        "Sivaram",
        style: mystyle(16, Colors.black, FontWeight.w700),
      )
    ],
  );
}

Upvotes: 3

Views: 2933

Answers (2)

Adelina
Adelina

Reputation: 11941

You could use flutter_staggered_grid_view

  StaggeredGridView.count(
    crossAxisCount: 4,
    children: List.generate(
        3,
        (index) => Center(
              child: CircleAvatar(
                radius: 64,
                backgroundColor: Colors.pink,
              ),
            )),
    staggeredTiles: [
      StaggeredTile.count(2, 2), // takes up 2 rows and 2 columns space
      StaggeredTile.count(2, 1), // takes up 2 rows and 1 column
      StaggeredTile.count(1, 2), // takes up 1 row and 2 column space
    ], // scatter them randomly
  );

enter image description here

Upvotes: 3

Ash Khachatryan
Ash Khachatryan

Reputation: 455

You can create class Person, and store profile name and image,

class Person {
  String name;
  String imageUrl;
}

and in your code can store all your persons in array

List<Person> persons = [Person(), Person(),....]


Wrap(
   spacing: 30,
   children: _children
);

List<Widget> _children {
  List<Widget> _widgets = List<Widget>();
  List<Persons> _randomList = persons.shuffle();
   
  _randomList.forEach((person) {
      _widgets.add(_buildProfile(person))
   });

  return _widgets;
}


Upvotes: -1

Related Questions