Flutter – Logic to create buttons within the app. Gridview, Listview or something else?

Issue

I am sorry to ask this question as I am very new to flutter and it may seem like a stupid one. I am trying to create an app that will create buttons at specific positions. I have checked the docs on flutter and could not find anything. Please help only with the logic that needs to be used and I will reasearch the rest. (Any additional help is appreciable). Below are the screenshots of what I want to achieve.

enter image description here

enter image description here

Solution

Follow the code-comment for details.

 List<int> data = [];

  ///tap event to increment the grid item
  void onTap() {
    setState(() {
      data.add(3); //random value
    });
  }
 /// adding button
  Widget addButton() {
    return GestureDetector(
      onTap: onTap,
      child: const Icon(
        Icons.add_circle,
        size: 45,
        color: Colors.black,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: data.isEmpty
          ? Center(
              /// you can use Align widget
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  addButton(),
                  Text("Nothing to show here"),
                ],
              ),
            )
          : GridView.count(
              crossAxisCount: 3,
              crossAxisSpacing: 10,
              mainAxisSpacing: 10,
              children: [
                ...data.map(
                  (e) => InkWell(
                    onTap: () {
                      print(e.toString());
                    },
                    child: Container(
                      color: Colors.deepOrange,
                    ),
                  ),
                ),

                /// add button
                addButton(),
              ],
            ),
    );
  }

Answered By – Yeasin Sheikh

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *