Изменение унаследованного виджета на отслеживание состояния не работает - PullRequest
0 голосов
/ 04 августа 2020

Итак, у меня есть виджет, который я хочу сделать с отслеживанием состояния, чтобы можно было добавлять анимацию к изображению. Однако этот виджет наследует конечные переменные от другого класса, и когда я делаю его с отслеживанием состояния, он перестает работать должным образом. Любая помощь приветствуется.

Итак, вот последний класс:

class Result extends GetPicture {
Result(int resultScore, Function resetHandler)     //Here's the inherited values
  : super(resetHandler, resultScore);

@override
Widget build(BuildContext context) {
return Scaffold(
  backgroundColor: Colors.black87,
  body: ListView(
    children: <Widget>[
      GetPicture(resetHandler, resultScore),
      Align(
        alignment: Alignment.center,
        child: RaisedButton(
          child: Text(
            'Restart Quiz!',
            style: TextStyle(fontSize: 20),
          ),
          textColor: Colors.blue,
          onPressed: resetHandler,
        ),
      )
    ],
  ),
);
}
}

Вот класс, от которого он наследуется:

// i want to make this stateful:

class GetPicture extends StatelessWidget {
final int resultScore;
final Function resetHandler;
GetPicture(this.resetHandler, this.resultScore);

@override
Widget build(BuildContext context) {
AlignmentDirectional _standAlignment = AlignmentDirectional(0.0, 0.7);

Widget child;
if (resultScore <= 5) {
  child = Container(
      margin: EdgeInsets.only(top: 10),
      child: Column(children: <Widget>[
        Container(
          child: Text(
            'You Got Star Platinum!',
            style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 30,
                color: Colors.white54),
          ),
        ),
        AnimatedContainer(
          duration: Duration(milliseconds: 500),
          alignment: _standAlignment,
          child: Image.asset('assets/images/stands/star platinum.jpg',
              height: 300, width: 200),
        ),
        Container(
            margin: EdgeInsets.only(right: 20, left: 20, bottom: 50),
            child: Text(
              'Star Platinum is a close-range Stand, with a basic reach of only 2 meters from Jotaros 
body, but with incredible strength, speed, and precision. It is one of the most powerful Stands 
featured in the series.',
              style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 20,
                  color: Colors.white54),
            ))
      ]));
} else if (resultScore > 5 && resultScore <= 10) {
  child = Container(
      margin: EdgeInsets.only(top: 10),
      child: Column(children: <Widget>[
        Container(
          child: Text(
            'You Got Hierophant Green!',
            style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 30,
                color: Colors.white54),
          ),
        ),
        Image.asset('assets/images/stands/H-green.jpg',
            height: 300, width: 200),
        Container(
            margin: EdgeInsets.only(right: 20, left: 20, bottom: 50),
            child: Text(
              'H-green is a close-range Stand, with a basic reach of only 2 meters from Jotaros body, but with incredible strength, speed, and precision. It is one of the most powerful Stands featured in the series.',
              style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 20,
                  color: Colors.white54),
            ))
      ]));
}

return new Container(child: child);
 }
 }

И это класс, который он получает это окончательные значения от:

import './quiz.dart';
import './result.dart';


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

class QuizPage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
// TODO: implement createState
return _MyAppState();
 }
 }

class _MyAppState extends State<QuizPage> {
var _questionIndex = 0;
var _totalScore = 0;
final _questions = const [
{
  'questionText': 'Which would Describe you best?',
  'answers': [
    {'text': 'Brash', 'score': 0},
    {'text': 'Confident', 'score': 1},
    {'text': 'Timid', 'score': 2},
    {'text': 'Nice', 'score': 3}
  ]
},
{
  'questionText': 'Which\'s mother toung of India?',
  'answers': [
    {'text': 'Marathi', 'score': 0},
    {'text': 'Gujarati', 'score': 1},
    {'text': 'Tamil', 'score': 2},
    {'text': 'Hindi', 'score': 3}
  ]
},
{
  'questionText': 'Who\'s prime ministor of India?',
  'answers': [
    {'text': 'Narendra Modi', 'score': 0},
    {'text': 'Amit Shah', 'score': 1},
    {'text': 'Sonia Gandhi', 'score': 2},
    {'text': 'Rahul Gandhi', 'score': 3}
  ]
},
{
  'questionText': 'Who\'s president of India?',
  'answers': [
    {'text': 'Lalkrishna Advani', 'score': 0},
    {'text': 'Barak Obama', 'score': 1},
    {'text': 'Ramnath Kovind', 'score': 2},
    {'text': 'Pratibha Patil', 'score': 3}
  ]
},
{
  'questionText': 'Who\'s Chief Minister of Gujarat?',
  'answers': [
    {'text': 'Nitin Patel', 'score': 0},
    {'text': 'Vijay Rupani', 'score': 1},
    {'text': 'Jayesh Radadiya', 'score': 2},
    {'text': 'Paresh Dhanani', 'score': 3}
  ]
},
{
  'questionText':
      'Which of the following was the author of the Arthashastra?',
  'answers': [
    {'text': 'Kalhan', 'score': 0},
    {'text': 'Visakhadatta', 'score': 1},
    {'text': 'Bana Bhatta', 'score': 2},
    {'text': 'Chanakya', 'score': 3}
  ]
},
];

void _resetQuiz() {
setState(() {
  _questionIndex = 0;
  _totalScore = 0;
});
}

 void _answerQuestions(int score) {
_totalScore += score;
setState(() {
  _questionIndex = _questionIndex + 1;
});
print('_questionIndex:$_questionIndex');
}

 @override
 Widget build(BuildContext context) {
// TODO: implement build

return MaterialApp(
  home: Scaffold(
    appBar: GradientAppBar(
      gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: <Color>[Colors.blue, Colors.black]),
      title: Text('Quiz App'),
    ),
    body: _questionIndex < _questions.length
        ? Quiz(
            questions: _questions,
            answerQuestions: _answerQuestions,
            questionIndex: _questionIndex)
        : Result(_totalScore, _resetQuiz),
  ),
 );
  }
}

1 Ответ

0 голосов
/ 05 августа 2020

Что вы можете сделать, так это использовать виджет с отслеживанием состояния следующим образом:

class Hello extends StatefulWidget {
  final hello;
  //final declared here

  const Hello({Key key, this.hello}) : super(key: key);

  @override
  _HelloState createState() => _HelloState();
}

class _HelloState extends State<Hello> {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: widget.hello, //called here
    );
  }
}

, то есть вы можете иметь окончательные значения, а затем вы можете вызывать их, используя widget.variablename, и он будет работать

...