1
votes

La mise à jour avec statefull ne fonctionne pas pour le flutter

J'ai essayé d'exécuter ce code dans Dart. quand je clique sur n'importe quel RaisedButton , cela ne passe pas à la question suivante. Il montre la sortie suivante dans la console VSCode.

I / flutter (7433): Réponse 2

Je serai très heureux si vous êtes en mesure de me guider à ce sujet. Ci-dessous le code pour fléchettes.

import 'package:flutter/material.dart';

//void main() {
//runApp(MyApp());
//}

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

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

class MyAppState extends State<MyApp> {
  var questionIndex = 0;

  void answerQuestion() {
    setState(() {
          questionIndex = questionIndex + 1;

    });
    print(questionIndex);
  }

  @override
  Widget build(BuildContext context) {
    var questions = [
      'What\'s your favorite color?',
      'What\'s your favorite animal?',
    ];
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: Text('My First App'),
          ),
          body: Column(
            children: [
              Text 
                  (questions[questionIndex]), 
              RaisedButton(
                child: Text('Answer 1'),
                onPressed: () => print('Answer 1'),
              ),
              RaisedButton(
                child: Text('Answer 2'),
                onPressed: () => print('Answer 2'),
              ),
              RaisedButton(
                child: Text('Answer 3'),
                onPressed: () => print('Answer 3'),
              ),
            ],
          )),
    );
  }
}


1 commentaires

Si la réponse vous a aidé, veuillez la marquer comme correcte


3 Réponses :


0
votes

ajoutez votre answerQuestion fonction dans onPress :

onPressed: () {
     print('Answer 1');
     answerQuestion();
     }

La prochaine étape est peut-être de considérer ce que si l'indice est> = 2.


0 commentaires

0
votes

Utilisez le code suivant:

import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MyAppState();
  }
}

class MyAppState extends State<MyApp> {
  var questionIndex = 0;
  var questions = [
    'What\'s your favorite color?',
    'What\'s your favorite animal?',
  ];

  void answerQuestion() {
    setState(() {
      if (questionIndex < questions.length - 1)
        questionIndex = questionIndex + 1;
      else
        print("index ranged reached");
    });
    print(questionIndex);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('My First App'),
        ),
        body: Column(
          children: [
            Text(questions[questionIndex]),
            RaisedButton(
              child: Text('Answer 1'),
              onPressed: answerQuestion,
            ),
            RaisedButton(
              child: Text('Answer 2'),
              onPressed: answerQuestion,
            ),
            RaisedButton(
              child: Text('Answer 3'),
              onPressed: answerQuestion,
            ),
          ],
        ),
      ),
    );
  }
}

Attribuez la référence de fonction answerQuestion à la propriété onPressed . Par conséquent, lorsque vous cliquez sur le bouton, il appellera setState


0 commentaires

0
votes

Les meilleures pratiques ont montré que nous devons éviter de déclarer trop de widgets / layout imbriqués au même endroit. ce que je suggérerais, c'est de séparer le widget scafold et de le déclarer en tant que classe qui étend StatefulWidget. voir l'exemple ci-dessous:

// Question Screen - Stateful
class QuestionScreen extends StatefulWidget {
  QuestionScreen({Key key}) : super(key: key);

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

class _QuestionScreenState extends State<QuestionScreen> {
  
  // Must have 3 questions
  var questions = [
      'What\'s your favorite color?',
      'What\'s your favorite animal?',
      'What\ s your favorite City?'
    ];
  var questionIndex = 0;

  void answerQuestion() {
    // The issue is here where after first question it is not getting updated 
    // the index is out of range.
    // you may either add one nore quetion to the list and wrap this with conditional statement.
    if (questions.length - 1  == questionIndex) return;
      questionIndex = questionIndex + 1;
      print("question index is : $questionIndex");
      setState((){});
    
  }
  
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Questions',),),
      body: Column(
            children: [
              Text 
                  (questions[questionIndex]), 
              Expanded(child:  
                ListView.builder(
                  itemBuilder: (context, index) => RaisedButton(
                    child: Text('Answer ${index + 1}'),
                    onPressed: answerQuestion,
                    ),
                  itemCount: questions.length,
                ),
             ),
              
            ],
         ),
    );
  }
} 

Cependant, si j'étais vous, j'aurais créé mes boutons de manière dynamique en fonction de la longueur de ma question comme celle-ci.

import 'package:flutter/material.dart';


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

// MyApp Class - Stateless
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: QuestionScreen(),
    );
  }
}

// Question Screen - Stateful
class QuestionScreen extends StatefulWidget {
  QuestionScreen({Key key}) : super(key: key);

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

class _QuestionScreenState extends State<QuestionScreen> {
  
  // Must have 3 questions
  var questions = [
      'What\'s your favorite color?',
      'What\'s your favorite animal?',
      'What\ s your favorite City?'
    ];
  var questionIndex = 0;

  void answerQuestion() {
    // The issue is here where after first question it is not getting updated 
    // the index is out of range.
    // you may either add one nore quetion to the list and wrap this with conditional statement.
    if (questions.length - 1  == questionIndex) return;
      questionIndex = questionIndex + 1;
      print("question index is : $questionIndex");
      setState((){});
    
  }
  
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Questions',),),
      body: Column(
            children: [
              Text 
                  (questions[questionIndex]), 
              RaisedButton(
                child: Text('Answer 1'),
                onPressed: answerQuestion,
              ),
              RaisedButton(
                child: Text('Answer 2'),
                onPressed: answerQuestion,
              ),
              RaisedButton(
                child: Text('Answer 3'),
                onPressed: answerQuestion,
              ),
            ],
         ),
    );
  }
}


0 commentaires