簡體   English   中英

如何在一個班級中在顫振中制作多個可重用的小部件?

[英]How to make multiple reusable widgets in flutter in one class?

我知道如何在課堂上制作一個項目小部件並在整個應用程序中使用它,如下所示:

import 'package:flutter/material.dart';

class MenuButtons extends StatelessWidget {

  final String titleName;
  final String goTo;
  final double width;
  final double height;

  MenuButtons(this.titleName,{this.goTo, this.width, this.height});

  @override
  Widget build(BuildContext context) {

    return Container(
      margin: EdgeInsets.all(10.0),
      width: width,
      height: height !=null ? height : 50.0,

      child: RaisedButton(
        color: Color.fromRGBO(121, 85, 72, 1.0),
        elevation: 5.0,
        child: Text(
          titleName,
          style: TextStyle(fontSize: 18.0, color: Colors.white),
        ),
        onPressed: () {

           Navigator.pushReplacementNamed(context, goTo);
        },
      ),
    );
  }
}

用法如下:

MenuButtons('Title',goTo: 'NextScreen',width: 350.0,),

現在,如果我想要更多的小部件,我可以使用相同的類,但可能具有不同的構造函數,或者我是否需要為我想在多個地方使用的每個小部件使用單獨的類...

如果新類只有一些與構建方法無關的參數,您可以這樣聲明,例如新類 IndexMenuButtons

class IndexMenuButtons extends MenuButtons{
   final int buttonIndex;
   ColorMenuButtons(String titleName, this.buttonIndex, {String goTo, double width, double height}) : super(titleName, goTo, width, height);
}

用法:

var btn = IndexMenuButtons('Title', 100, goTo: 'NextScreen',width: 350.0);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM