create dynamic widget in flutter

 A dynamic widget in Flutter is a widget that changes according to the data at runtime. Meaning, if you are fetching data from an API or Firebase and want to update widgets based on that, then you use dynamic widgets.

Today in this post we will learn to make a dynamic list inside which there will be an icon and then a text and then we will learn to put the back icon of the iPhone. Follow all the steps told by us.

First of all, create your flutter project. You can use Android studio or vs code. The process is same for both. When you create a flutter project, a file named .dot is created by default. And then you can paste the code given by us inside that file and your list will be ready.


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


class AccountDetail extends StatefulWidget {
  @override
  _AccountDetailState createState() => _AccountDetailState();
}

class _AccountDetailState extends State{
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("App Bar"),
      ),
    
    body: Container(
      child: Column(
        children: [
          Expanded(child: Container(
            child: ListView(
              children: [
                Container(
                  color: Colors.blue,
                  child: Column(
                 children: [
                  buildMenuItem(Icons.home, "Dashboard", context,),
                ],
            ),

                ),
                buildMenuItem(Icons.home, "Dashboard", context,),
                buildMenuItem(Icons.home, "Dashboard", context,),
              ],
            ),
          ))
        ],
      ),
    ),
    
    );
  }

  Widget buildMenuItem(IconData icon, String title, BuildContext context, [Widget? screen, Color? iconColor]) {
    return ListTile(
      leading: Container(
        alignment: Alignment.center,
        child: Row(
          children: [
            Icon(icon, color: iconColor ?? Colors.black),
            SizedBox(width: 10,),
            Text(title, style: TextStyle(fontSize: 16)),
            Spacer(),
            Icon(Icons.arrow_forward_ios, size: 16),
          ],
        ),
      ),

      onTap: () {
        if (screen != null) {
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => screen),
          );
        }
      },
    );
  }
}

  Code Explanation
  • Flutter package has been imported in this project.
  • The scaffold has been returned and a bar has been placed inside it.
  • The pen is taken and the list view is taken inside the pen. All the properties of the widget are being applied.
  • A widget named buildMenuItem is created inside which icon, title and context are passed.

 Output


 

Post a Comment

0 Comments