Home > Software engineering >  How to shorten the flutter dart code below to a function?
How to shorten the flutter dart code below to a function?

Time:03-12

I am having a tough time shortening the code below to a function. I am looking to duplicate the elevated button below to hundreds of buttons in my screen hence believe function is the best way to do so, then I can just call the function in my page.

ElevatedButton(
            style:
                TextButton.styleFrom(backgroundColor: Colors.grey.shade200),
            child: Align(
              alignment: Alignment.centerLeft,
              child: RichText(
                textAlign: TextAlign.justify,
                text: TextSpan(
                  children: <TextSpan>[
                    TextSpan(
                      text: "Diploma in Business | ",
                      style: TextStyle(color: Colors.black),
                    ),
                    TextSpan(
                      text: "Taylor\u0027s",
                      style: TextStyle(
                          color: Colors.black, fontWeight: FontWeight.bold),
                    ),
                  ],
                ),
              ),
            ),
            onPressed: () {
              sendAnalyticsEvent(
                  eventName: "diplomainbusiness_taylors",
                  clickevent: "User clicked dipt");
              showModalBottomSheet(
                isScrollControlled: true,
                context: context,
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.vertical(
                  top: Radius.circular(20),
                )),
                builder: (context) => Container(
                  padding: EdgeInsets.all(16),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [        
                            Image.network(
                              'https://i.imgur.com/bcAC3cA.jpg',
                                 loadingBuilder: (context, child, loadingProgress) {
                                 if (loadingProgress == null) return child;
                                   return const CircularProgressIndicator();      
                                 },
                                 errorBuilder: (context, error, stackTrace) =>
                                 const Text('Some errors occurred!'),
                            ),
                      ListTile(
                        title: Text(
                          '\nThis programme is specifically designed to equip students with solid business knowledge and skills, with a central focus on instilling a global mindset as well as creative and critical thinking, set in an experimental learning environment. Upon successful completion of the programme, students will be able to seamlessly transition into our degree and have the competitive advantage required to seek global employment opportunities.\n',
                          textAlign: TextAlign.justify,
                        ),
                      ),
                      ListTile(
                        title: Text(
                          '• April and August Intake \n• 2 years programme\n• Scholarships available',
                          textAlign: TextAlign.justify,
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.all(10.0),
                        child: Container(
                          width: double.infinity,
                          child: CupertinoButton.filled(
                            child: Text("Interested? Get more info!"),
                            onPressed: () => openBrowserTab(),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              );
            },
          ),

Basically, the elevated button will trigger a bottom sheet and inside the bottom sheet, there is an image, a few texts (List tile) and so. Is it possible to make this into a function or nah this is the shortest code possible? Kindly need some guidance on this.

Thank you so much!

CodePudding user response:

Declare it like this

import 'package:flutter/material.dart';

class CustomElevatedButton extends StatelessWidget {
  final String name;
  final String education;
  final String eventName;
  final String clickEvent;
  final String imageURl;
  final String errorMessage;
  final String information1;
  final String information2;
  final String information3;

  const CustomElevatedButton(
      {Key? key,
      required this.name,
      required this.education,
      required this.eventName,
      required this.clickEvent,
      required this.imageURl,
      required this.errorMessage,
      required this.information1,
      required this.information2,
      required this.information3})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      style: TextButton.styleFrom(backgroundColor: Colors.grey.shade200),
      child: Align(
        alignment: Alignment.centerLeft,
        child: RichText(
          textAlign: TextAlign.justify,
          text: TextSpan(
            children: <TextSpan>[
              TextSpan(
                text: education,
                style: const TextStyle(color: Colors.black),
              ),
              TextSpan(
                text: name,
                style:
                    const TextStyle(color: Colors.black, fontWeight: FontWeight.bold),
              ),
            ],
          ),
        ),
      ),
      onPressed: () {
        sendAnalyticsEvent(
            eventName: eventName,
            clickevent: clickEvent);
        showModalBottomSheet(
          isScrollControlled: true,
          context: context,
          shape: const RoundedRectangleBorder(
              borderRadius: const BorderRadius.vertical(
            top: Radius.circular(20),
          )),
          builder: (context) => Container(
            padding: const EdgeInsets.all(16),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Image.network(
                  imageURl,
                  loadingBuilder: (context, child, loadingProgress) {
                    if (loadingProgress == null) return child;
                    return const CircularProgressIndicator();
                  },
                  errorBuilder: (context, error, stackTrace) =>
                       Text(errorMessage),
                ),
                ListTile(
                  title: Text(
                    information1,
                    textAlign: TextAlign.justify,
                  ),
                ),
                ListTile(
                  title: Text(
                    information2,
                    textAlign: TextAlign.justify,
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(10.0),
                  child: Container(
                    width: double.infinity,
                    child: CupertinoButton.filled(
                      child: Text(information3),
                      onPressed: () => openBrowserTab(),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}

use it like this

const CustomElevatedButton(
              clickEvent: 'User clicked dipt',
              education: 'Diploma in Business | ',
              errorMessage: 'Some errors occurred!',
              eventName: 'diplomainbusiness_taylors',
              imageURl: 'https://i.imgur.com/bcAC3cA.jpg',
              information1: '\nThis programme is specifically designed to equip students with solid business knowledge and skills, with a central focus on instilling a global mindset as well as creative and critical thinking, set in an experimental learning environment. Upon successful completion of the programme, students will be able to seamlessly transition into our degree and have the competitive advantage required to seek global employment opportunities.\n',
              information2: '• April and August Intake \n• 2 years programme\n• Scholarships available',
              information3: 'Interested? Get more info!',
              name: 'Taylor\u0027s',
            ),

You can extract anything you want including the styles and onpressed callbacks.

If you have any doubts feel free to ask.

  • Related