Сделайте определенное действие c доступным только для одной кнопки - PullRequest
0 голосов
/ 09 мая 2020

Я новичок в flutter и OOP в целом, я делаю приложение, которое предлагает вам выбрать статью для немецкого слова. Я хочу знать, как изменить цвет нажатой кнопки только в зависимости от того, правильный ответ или нет, и отключить все кнопки одновременно. но при нажатии все 3 кнопки меняют цвет и отключаются.

вот мой класс кнопок

import 'package:flutter/material.dart';

class ArticleButton extends StatelessWidget {
  @override
  final String article;
  final Function check;
  final bool onPushed;
  final Color bgColor;
  ArticleButton({this.article,this.check,this.onPushed,this.bgColor});


  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: FlatButton(
        onPressed: onPushed? check:null,
        child: Text(
            "$article",
        style: TextStyle(
          fontSize: 20.0,
          fontFamily: 'Roboto',
        ),),
        splashColor: Colors.grey,
        disabledColor: bgColor,


      ),
    );
  }
}

вот моя основная функция

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'services/word.dart';
import 'package:germanarticle/button.dart';

void main() {
  runApp(MaterialApp(
    home: Home(),
  ));
}
class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}



class _HomeState extends State<Home> {
  List<Word> words =[
    Word(article: "Der",word: "Apfel"),
    Word(article: "Die",word: "Erdbeere"),
    Word(article: "Das",word: "Auto"),
  ];

  List<String> articles=['Der',"Die","Das"];
  int index =0;
  int score =0;
  bool enabled=true;
  Color bgColor=Colors.blue;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text("$score"),

          Text("${words[index].word}"
              ,style: TextStyle(
              fontSize: 60.0,
            ),
          ),
          SizedBox(
            height: 20.0,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children:

              articles.map((e)=>ArticleButton(
                  article:e,
                  check:(){
                    if (words[index].article == e){
                      setState(() {
                        score++;
                        bgColor=Colors.green;

                      }
                      );

                    }else{
                      setState(() {
                        enabled=false;
                        bgColor=Colors.red;


                      });
                    }

                  },onPushed: enabled,
                bgColor: bgColor,
                  )
              ).toList(),




          ),
          FlatButton(

            onPressed: () {
              setState(() {
              index++;
              enabled =true;

            });
            },
            child: Text("next"),


          )
        ],
      ),

    );
  }
}

спасибо

Ответы [ 2 ]

0 голосов
/ 09 мая 2020

Попробуйте, работает отлично:

// an enum for all your button state
enum ButtonStatus {correct, wrong }

// get the color of your button based on the button state
Color getButtonStatus(ButtonStatus buttonStatus) {
  switch (buttonStatus) {
    case ButtonStatus.correct:
      return Colors.green;
      break;
    case ButtonStatus.wrong:
      return Colors.red;
      break;
    default:
      return Colors.blue;
      break;
  }
}

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

class _HomeState extends State<Home> {
  List<Word> words = [
    Word(article: "Der", word: "Apfel"),
    Word(article: "Die", word: "Erdbeere"),
    Word(article: "Das", word: "Auto"),
  ];

  // define a button status object here
  ButtonStatus buttonStatus;

  List<String> articles = ['Der', "Die", "Das"];
  int index = 0;
  int score = 0;
  Color bgColor = Colors.blue;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text("$score"),
          Text(
            "${words[index].word}",
            style: TextStyle(
              fontSize: 60.0,
            ),
          ),
          SizedBox(
            height: 20.0,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: articles
                .map((e) => ArticleButton(
                      article: e,
                      check: () {
                        if (words[index].article == e) {
                          setState(() {
                            score++;
                            // change the color of the button if correct
                            buttonStatus = ButtonStatus.correct;
                          });
                        } else {
                          setState(() {
                            // change the color of the button if wrong
                            buttonStatus = ButtonStatus.wrong;
                          });
                        }
                      },
                      onPushed: enabled,
                      bgColor: bgColor,
                    ))
                .toList(),
          ),
          FlatButton(
            // add the  color to your flat button, it changes if the answer is correct or wrong and if the button is disabled
            color: getButtonStatus(buttonStatus),
            onPressed: () {
              setState(() {
                index++;
              });
            },
            child: Text("next"),
          )
        ],
      ),
    );
  }
}

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

0 голосов
/ 09 мая 2020

Это потому, что вы не меняете свою индексную переменную внутри функции карты, поэтому она полностью равна 0. Предоставьте несколько скриншотов / зарисовок того, чего вы пытаетесь достичь с помощью приложения.

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