首页 > 解决方案 > 相对于颤动中另一页的值,无法更改一个页面中的值

问题描述

当我们单击另一个屏幕上的下一个按钮时,我想更改一个页面的索引值(象形图索引)。我将简要解释一下,我的场景中有 2 个屏幕,第一个屏幕包含一个图像及其名称、一个文本字段和下一个按钮(我提供一个虚拟数据包含一个图像列表及其名称)这背后的逻辑是,当我们完成文本字段框并单击下一步按钮(验证后)时,文本字段值检查我在虚拟数据中给出的正确值并显示它也提供的同义词。当我们单击下一个按钮时,我们将转到另一个页面,其中包含正确答案(从第一页传递)和一个文本字段,当单击此页面中的下一步按钮时,用户可以写下正确答案(已验证)(直到这是我的应用程序完美)我想加载第一页,它的索引已更新(+1),我初始化为 0(var pictogramindex=0)。但在我的情况下,当返回第一页时,索引没有更新,它会自动存储初始化值。我想要的是当我单击第二页中的下一步按钮时,我想更新第一页上的索引

我的第一个屏幕的源代码显示在这里

class Pictogramscreen extends StatefulWidget {
  final int length;

  const Pictogramscreen({Key key, this.length}) : super(key: key);
  @override
  _PictogramscreenState createState() => _PictogramscreenState();
}

class _PictogramscreenState extends State<Pictogramscreen> {
  @override
  final _Key = GlobalKey<FormState>();
  Color defaultcolor = Colors.blue[50];
  Color trueColor = Colors.green;
  Color falseColor = Colors.red;

  Widget defcorrect = Text('');
  var pictogramindex = 0;

  TextEditingController usertitleInput = TextEditingController();

  nextPictogram() {
    setState(() {
      pictogramindex++;
    });
  }

  fillColor() {
    setState(() {
      usertitleInput.text == pictdata[pictogramindex]['pictcorrectword']
          ? defaultcolor = trueColor
          : defaultcolor = falseColor;
    });
  }

  correctText() {
    setState(() {
      usertitleInput.text == pictdata[pictogramindex]['pictcorrectword']
          ? defcorrect = Text(pictdata[pictogramindex]['pictsynonym'])
          : defcorrect = Text(pictdata[pictogramindex]['pictcorrectword']);
    });
  }

  reset() {
    setState(() {
      defaultcolor = Colors.blue[50];
      defcorrect = Text('');

      usertitleInput.clear();
    });
  }

  void description(BuildContext ctx) {
    Navigator.of(context).pushNamed('/user-description', arguments: {
      'id': pictdata[pictogramindex]['pictid'],
      'word': pictdata[pictogramindex]['pictcorrectword']
    });
  }

  Widget build(BuildContext context) {
    int length = pictdata.length;

    return Scaffold(
        body: pictogramindex < pictdata.length
            ? ListView(
                children: <Widget>[
                  Container(
                    margin: EdgeInsets.only(top: 20),
                    padding: EdgeInsets.all(15),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Card(
                          margin: EdgeInsets.only(top: 20),
                          child: Image.network(
                              pictdata[pictogramindex]['pictimg']),
                        ),
                        SizedBox(
                          height: 10,
                        ),
                        Text(
                          pictdata[pictogramindex]['pictword'],
                          style: TextStyle(
                            fontSize: 25,
                          ),
                        ),
                        SizedBox(
                          height: 10,
                        ),
                        //Card(
                        //color: Colors.blue,
                        // child: TextField(
                        // decoration: InputDecoration.collapsed(
                        // hintText: 'type here'),
                        //textAlign: TextAlign.center,
                        // onSubmitted: (value) {
                        // usertitleInput = value;

                        // print(usertitleInput);
                        // },
                        // ),
                        //),

                        Form(
                          key: _Key,
                          child: TextFormField(
                              controller: usertitleInput,
                              validator: (usertitleInput) {
                                if (usertitleInput.isEmpty) {
                                  return 'Answer cannot be empty';
                                } else {
                                  return null;
                                }
                              },
                              textAlign: TextAlign.center,
                              decoration: InputDecoration(
                                enabledBorder: OutlineInputBorder(
                                    borderSide:
                                        BorderSide(color: Colors.blueAccent),
                                    borderRadius: BorderRadius.all(
                                      Radius.circular(15),
                                    )),
                                labelText: 'Type your Answer',
                                filled: true,
                                fillColor: defaultcolor,
                              ),
                              onFieldSubmitted: (value) {
                                usertitleInput.text = value;
                                fillColor();
                                correctText();
                                print(usertitleInput.text);
                              }),
                        ),
                        SizedBox(
                          height: 10,
                        ),
                        defcorrect,
                        SizedBox(
                          height: 10,
                        ),
                        RaisedButton(
                          onPressed: () {
                            if (_Key.currentState.validate()) {
                              description(context);
                              // nextPictogram();
                              reset();
                            }
                            //
                            //if (_Key.currentState.validate() == correctText()) {
                            //  nextPictogram;
                            // }
                          },
                          child: Text('Next'),
                        )
                      ],
                    ),
                  ),
                ],
              )
            : Center(
                child: Text('completed'),
              ));
  }
}



我的第二个屏幕的源代码显示在这里

class Userinputscreen extends StatefulWidget {
  final String id;
  final String word;

  const Userinputscreen({Key key, this.id, this.word}) : super(key: key);

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

class _UserinputscreenState extends State<Userinputscreen> {
  final _Keey = GlobalKey<FormState>();

  TextEditingController userdescription = TextEditingController();
  var pictogramindex;

  void nextpict(BuildContext context) {
    Navigator.of(context).pushNamed('/main-screen');
  }
  // void nextpict(BuildContext context, int index) {
  //   Navigator.push(
  //       context,
  //       MaterialPageRoute(
  //           builder: (ctx) => Pictogramscreen(
  //                 index: i = 0,
  //               )));
  // }

  @override
  Widget build(BuildContext context) {
    final routeArgs =
        ModalRoute.of(context).settings.arguments as Map<String, String>;

    final correctWord = routeArgs['word'];
    return MaterialApp(
      home: Scaffold(
          body: ListView(children: <Widget>[
        Padding(
          padding: EdgeInsets.only(top: 50),
          child: Center(
            child: Container(
              padding: EdgeInsets.all(20),
              margin: EdgeInsets.only(top: 100),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    correctWord,
                    style: TextStyle(fontSize: 26),
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  Form(
                    key: _Keey,
                    child: TextFormField(
                        controller: userdescription,
                        validator: (userdescription) {
                          if (userdescription.isEmpty) {
                            return 'Answer cannot be empty';
                          } else {
                            return null;
                          }
                        },
                        textAlign: TextAlign.center,
                        decoration: InputDecoration(
                          enabledBorder: OutlineInputBorder(
                              borderSide: BorderSide(color: Colors.blueAccent),
                              borderRadius: BorderRadius.all(
                                Radius.circular(15),
                              )),
                          labelText: 'Type your Answer',
                          filled: true,
                        ),
                        onFieldSubmitted: (value) {
                          userdescription.text = value;

                          print(userdescription.text);
                        }),
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  RaisedButton(
                    onPressed: () {
                      if (_Keey.currentState.validate()) {
                        nextpict(context);
                      }
                    },
                    child: Text('Next'),
                  )
                ],
              ),
            ),
          ),
        ),
      ])),
    );
  }
}


标签: flutter

解决方案


如果我做对了,您基本上想告诉初始页面它的状态已在其他地方更新(索引)。你基本上需要让你的应用程序“反应”。

正如谷歌开发者教程中所说:

Flutter 的优点之一是它使用响应式视图,您可以通过将响应式原理应用到应用程序的数据模型来将其提升到一个新的水平。

使用某种状态管理。您需要选择并使用BlocInheritedWidget 和 InheritedModelProvider(ScopedModel)等。

查看有关有关状态管理的 Flutter 的这篇文章,或者查看完整的方法列表


推荐阅读