Упростить строки кнопок в вызываемую функцию - PullRequest
0 голосов
/ 03 мая 2020

Я работаю над проектом домашней автоматизации, который включает в себя несколько кнопок! Но только сейчас я столкнулся с этой маленькой проблемой, потому что в моем проекте слишком много строк, из-за чего сложно найти что-то, что можно изменить, когда это необходимо. Как я могу создать класс или функцию, которая вызывает все эти кнопки для класса Home, чтобы он не был слишком сложным. Но я все еще хочу иметь возможность менять кнопки нормально, без проблем. если возможно, создание файла keys.dart со всеми этими кнопками останется.

Если вы прокрутите немного вниз, вы увидите, где начинаются кнопки, это прокомментировано. Я не вставил все свои кнопки, потому что у меня более 500 строк.


Вот что у меня есть:

class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

int bateria = 100;

@override
Widget build(BuildContext context) {
return Scaffold(
  backgroundColor: Colors.grey[800],
  appBar: AppBar(
    backgroundColor: Colors.grey[700],
    title: Row(
      children: <Widget>[
        Title(
          color: Colors.white,
          child: Icon(
            Icons.adjust,
            color: Colors.green,
          ),
        ),
        Padding(
          padding: const EdgeInsets.only(left: 5),
          child: Text(
            "Bem Vindo Nilton",
            style: TextStyle(color: Colors.black),
          ),
        ),
      ],
    ),
  ),
  body: SingleChildScrollView(
    child: ConstrainedBox(
      constraints: BoxConstraints(),
      child: Padding(
        padding: EdgeInsets.fromLTRB(20, 20, 20, 0),
        child: Column(
          children: <Widget>[
            Align(
              alignment: Alignment.center,
              child: Text(
                'Brazil, Paraná, Curitiba',
                style: TextStyle(
                  color: Colors.black,
                  letterSpacing: 1,
                  fontSize: 15,
                ),
              ),
            ),
            Row(
              children: <Widget>[
                Padding(
                  padding: EdgeInsets.only(left: 130),
                  child: Text(
                    '23°C',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      color: Colors.black,
                      letterSpacing: 1,
                      fontSize: 50,
                    ),
                  ),
                ),
                //invert_colors
                Padding(
                  padding: new EdgeInsets.only(left: 83),
                  child: new FittedBox(
                    fit: BoxFit.none,
                    child: new Icon(Icons.invert_colors, size: 15,),
                  ),
                ),
                Text(
                  '80%',
                  style: TextStyle(
                    color: Colors.black,
                    letterSpacing: 1,
                    fontSize: 15,
                  ),
                ),
              ],
            ),
            Divider(
              height: 30.0,
              color: Colors.grey[600],
            ),
            Align(
              alignment: Alignment.centerLeft,
              child:Text(
                "23:05",
                style: TextStyle(
                  color: Colors.black,
                  letterSpacing: 1,
                  fontSize: 30,
                ),
              ),
            ),
            Divider(
              height: 25.0,
              color: Colors.grey[600],
            ),
            /*


             Buttons start here
            Botões 1 Fileira


             */
            Column(
              children: <Widget>[
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    ClipRRect(
                      borderRadius: BorderRadius.circular(10),
                      child: SizedBox(
                        width: 90.0,
                        height: 90.0,
                        child: RaisedButton(
                          // remove the default padding the raised button has
                          padding: EdgeInsets.zero,
                          onPressed: () {
                            setState(() {
                              bateria -= 1;
                              if (bateria <= 0)
                              {
                                bateria = 0;
                              }
                            });
                          },
                          color: Colors.grey,
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: <Widget>[
                              Row(
                                children: <Widget>[
                                  Padding(
                                    padding: EdgeInsets.only(top: 5,right: 8, bottom: 10),
                                    child: Icon(
                                      Icons.stay_primary_portrait,
                                      size: 35,
                                    ),
                                  ),
                                  Padding(
                                    padding: EdgeInsets.only(top: 7,left: 0,right: 0, bottom: 0),
                                    child: new FittedBox(
                                      fit: BoxFit.none,
                                      child: new Icon(Icons.battery_charging_full, size: 10,),
                                    ),
                                  ),
                                  Padding(
                                    padding: EdgeInsets.only(top: 0,right: 0, bottom: 10, left: 0),
                                    child: Text("Lock\n$bateria%"),
                                  ),
                                ],
                              ),
                              Padding(
                                padding: EdgeInsets.only(top: 8, right: 17),
                                child: Text(
                                  "Door Lock \nGarage",
                                  style: TextStyle(fontSize: 13),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                    SizedBox(width: 30.0),
                    //Botao 2
                    ClipRRect(
                      borderRadius: BorderRadius.circular(10),
                      child: SizedBox(
                        width: 90.0,
                        height: 90.0,
                        child: RaisedButton(
                          // remove the default padding the raised button has
                          padding: EdgeInsets.zero,
                          onPressed: () {
                          },
                          color: Colors.grey,
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: <Widget>[
                              Row(
                                children: <Widget>[
                                  Padding(
                                    padding: EdgeInsets.only(top: 5,right: 25, bottom: 10),
                                    child: Icon(
                                      Icons.lightbulb_outline,
                                      size: 35,
                                    ),
                                  ),
                                  Padding(
                                    padding: EdgeInsets.only(top: 0,right: 0, bottom: 20, left: 0),
                                    child: Text("On"),
                                  ),
                                ],
                              ),
                              Padding(
                                padding: EdgeInsets.only(top: 8, right: 17),
                                child: Text(
                                  "Lâmpada 1\nSchuma",
                                  style: TextStyle(fontSize: 13),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),

Попытка:

class CustomButton extends StatelessWidget {
// define this parameters as you will need them
final Function onPressed;
final IconData icon;
final String text;
final String text2;

// define a constructor for the class custom button
CustomButton({this.onPressed, this.icon, this.text, this.text2});

@override
Widget build(BuildContext context) {
return ClipRRect(
  borderRadius: BorderRadius.circular(10),
  child: SizedBox(
    height: 90.0,
    width: 90.0,
    child: RaisedButton(
      padding: EdgeInsets.zero,
      color: Colors.grey,
      onPressed: onPressed,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Row(
            children: <Widget>[
              Padding(
                padding: EdgeInsets.only(top: 5, right: 25, bottom: 10),
                child: Icon(
                  // assign the defined icon above to the icon here
                  icon,
                  size: 35,
                ),
              ),
              Padding(
                padding:
                EdgeInsets.only(top: 0, right: 0, bottom: 20, left: 0),
                // assign the defined string above to the text here
                child: Text(text),
              ),
              Padding(
                padding: EdgeInsets.only(top: 8, right: 17),
                child: Text(
                  text2,
                  style: TextStyle(fontSize: 13),
                ),
              ),
            ],
          ),
        ],
      ),
    ),
  ),
);
}
}

1 Ответ

1 голос
/ 03 мая 2020

Да, возможно, вы можете определить класс с именем CustomButton, как показано ниже:

class CustomButton extends StatelessWidget {
  // define this parameters as you will need them
  final Function onPressed;
  final IconData icon;
  final String text;

  // define a constructor for the class custom button
  CustomButton({this.onPressed, this.icon, this.text});

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(10),
      child: SizedBox(
        height: 90.0,
        width: 90.0,
        child: FlatButton(
          // remove the default padding the raised button has
          padding: EdgeInsets.zero,
          // assigned the defined onpressed function above to the one here
          onPressed: onPressed,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Row(
                children: <Widget>[
                  Padding(
                    padding: EdgeInsets.only(top: 5, right: 25, bottom: 10),
                    child: Icon(
                      // assign the defined icon above to the icon here
                      icon,
                      size: 35,
                    ),
                  ),
                  Padding(
                    padding:
                        EdgeInsets.only(top: 0, right: 0, bottom: 20, left: 0),
                    // assign the defined string above to the text here
                    child: Text(text),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Затем внутри вашего домашнего экрана вы можете вызывать CustomButton всякий раз, когда вам это нужно, вот так:

Row(
        children: <Widget>[
          // custom button 1 here
          CustomButton(
            icon: Icons.access_alarm,
            text: 'Button 1',
            onPressed: () => print('Do something'),
          ),

          // custom button 2 here
          CustomButton(
            icon: Icons.access_alarm,
            text: 'Button 2',
            onPressed: () => print('Do something'),
          ),

          // custom button 3 here
          CustomButton(
            icon: Icons.access_alarm,
            text: 'Button 3',
            onPressed: () => print('Do something'),
          ),
        ],
      ),
    );

Надеюсь, это поможет

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...