简体   繁体   中英

Reusing widgets in flutter/dart

I have the following Flutter code, and I'm trying to figure out how to put section 1 into a separate class so that I can reuse it on multiple screens, and then separately (not at the same time, but instead of), how to put section 2 (which is a larger portion of code) into a separate class and how to reuse that on multiple pages with a variable to be able to change the title. Currently, I'm just copying and pasting the entire code into each screen, but I know there has to be a better way by reusing code.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: Scaffold(

        //------------------START SECTION 2---------------------------------------------

        appBar: AppBar(
          backgroundColor: Colors.blue,
          title: Text(
            "Welcome",
            style: TextStyle(color: Colors.white),
          ),
          actions: <Widget>[
            // action button

            //------------------START SECTION 1---------------------------------------------

            PopupMenuButton<String>(
              //onSelected: showMenuSelection
              //icon: new Icon(Icons.add, color: Colors.blueGrey),
              itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[
                    const PopupMenuItem<String>(
                        value: 'Item 1', child: Text('Item 1')),
                    const PopupMenuItem<String>(
                        value: 'Item 2', child: Text('Item 2')),
                  ],
            ),

            //------------------END SECTION 1---------------------------------------------

          ],
        ),

        //------------------END SECTION 2---------------------------------------------

        body: Center(
          child: Text('Hello World'),
        ),
      ),
    );
  }
}

VS code lets you extract the widget with a few clicks, If you're using VS code - select the line where code for widget starts. Hit Ctrl + . , select Extract widget option, enter name of your choice. And then you can customize extracted widget to take in different parameters and return widget accordingly. Same can be done with any IDE, but I am unaware of the procedure.

Edit 1 : since I am unable to post screenshots right now, I found this SO answer that could help. :) https://stackoverflow.com/a/51235410/4794396

You can try this. I'm doing this way. I've created a class in which there's a function which holds my AppBar in main.dart file.

Example:

class MyAppBar {
  setAppBar(context, String title) {
    return new AppBar(
      backgroundColor: Colors.blue,
      title: Text(
        title,
        style: TextStyle(color: Colors.white),
      ),
      actions: <Widget>[
        // action button

        //------------------START SECTION 1---------------------------------------------

        PopupMenuButton<String>(
          //onSelected: showMenuSelection
          //icon: new Icon(Icons.add, color: Colors.blueGrey),
          itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[
                const PopupMenuItem<String>(
                    value: 'Item 1', child: Text('Item 1')),
                const PopupMenuItem<String>(
                    value: 'Item 2', child: Text('Item 2')),
              ],
        ),

        //------------------END SECTION 1---------------------------------------------
      ],
    );
  }
}

Usage will be, you have to import your main.dart file in the files where you want to set AppBar .

@override
Widget build(BuildContext context) {
  return Scaffold(
    backgroundColor: Color.fromRGBO(255, 255, 255, 20.0),
    appBar: MyAppBar().setAppBar(context, 'Title for AppBar'),
    body: new Container(), // your body goes here.
  );
}

You can set the popup menu the same way. I'll give an example but you'll have to make it work your way.

class PopupMenuButtonBuilder {
  setPopupButton() {
    return <Widget>[
      PopupMenuButton<String>(
        //onSelected: showMenuSelection
        //icon: new Icon(Icons.add, color: Colors.blueGrey),
        itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[
              const PopupMenuItem<String>(
                value: 'Item 1',
                child: Text(
                  'Item 1',
                ),
              ),
              const PopupMenuItem<String>(
                value: 'Item 2',
                child: Text(
                  'Item 2',
                ),
              ),
            ],
      ),
    ];
  }
}

Usage of above class will be:

// this `actions` is of `AppBar`.
actions: PopupMenuButtonBuilder().setPopupButton(),

If you want to have different name of the PopupMenuItem you can pass the title in setPopupButton() function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM