【问题标题】:How to make multiple reusable widgets in flutter in one class?如何在一个类中制作多个可重用的小部件?
【发布时间】:2020-05-10 04:17:42
【问题描述】:

我知道如何在课堂上制作一个 item-widget 并在整个应用程序中使用它,如下所示:

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,),

现在,如果我想拥有更多小部件,我可以使用相同的类,但可能使用不同的构造函数,或者我是否需要为每个要在多个地方使用的小部件单独的类...

【问题讨论】:

    标签: flutter widget code-reuse


    【解决方案1】:

    如果新类只有一些与构建方法无关的参数,你可以这样声明,例如新类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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      • 2021-04-09
      • 1970-01-01
      • 1970-01-01
      • 2019-07-18
      相关资源
      最近更新 更多