简体   繁体   English

setState 在 StatefulBuilder 内部更新,但在使用外部方法时不更新

[英]setState updating inside StatefulBuilder but not updating when using a method outside

I am having a showMyModalBottomSheet that calls showModalBottomSheet which returns StatefulBuilder that has some widgets .我有一个调用showMyModalBottomSheetshowModalBottomSheet ,它返回有一些widgetsStatefulBuilder The problem i am having is that if i setState it just works fine but if i setState in a method that i have called it does not work.我遇到的问题是,如果我setState它可以正常工作,但是如果我在我调用的方法中 setState 它不起作用。

Below is my showMyModalBottomSheet method下面是我的showMyModalBottomSheet方法


showMyModalBottomSheet() {
    showModalBottomSheet(
        context: context,
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(top: Radius.circular(25))),
        builder: (context) {

          return StatefulBuilder(builder: (context, setState) {
            return Container(
              padding: EdgeInsets.only(
                  bottom: MediaQuery.of(context).viewInsets.bottom),
              child: SingleChildScrollView(
                child: Container(
                  width: double.infinity,
                  child: Column(children: [
                  Container(
                    width: double.infinity,
                    margin: const EdgeInsets.only(
                        left: 10, right: 10, top: 20, bottom: 20),
                    child: Text(
                      _titleText,
                      textAlign: TextAlign.center,
                      style:
                          TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
                    ),
                  ),
                  Container(
                    width: double.infinity,
                    margin: const EdgeInsets.only(
                        left: 20, right: 20, top: 10, bottom: 10),
                    child: TextFormField(
                      key: _titleFormKey,
                      decoration: InputDecoration(labelText: "Enter Title"),
                      controller: _titleController,
                      validator: (title) {
                        if (title!.isEmpty) {
                          return "Please enter title";
                        } else {
                          return null;
                        }
                      },
                    ),
                  ),
                  Container(
                    child: ElevatedButton(
                      onPressed: () {
                        if (_titleFormKey.currentState!.validate()) {

                          // updating title
                          _titleText = _titleController.text.trim().toString();

                        }
                      },
                      child: Text("Update Title"),
                    ),
                  )
                ]),
              ),)
            );
          });
        });
  }

When i am updating my _titleText using below way it just works fine当我使用以下方式更新我的_titleText时,它工作正常


                     onPressed: () {
                        if (_titleFormKey.currentState!.validate()) {

                          _titleText = _titleController.text.trim().toString();

                        }
                      },

But when i am using my method updateTitle like below it does not update但是当我使用下面的方法updateTitle时,它​​不会更新


                     onPressed: () {
                        if (_titleFormKey.currentState!.validate()) {

                          updateTitle(_titleController.text.trim().toString());

                        }
                      },

And below is my updateTitle method下面是我的updateTitle方法


updateTitle(String title){
    setState(() {
      _titleText = title;
    });
  }

Below is my entire code下面是我的整个代码


import 'package:flutter/material.dart';

class MyPage extends StatefulWidget {
  const MyPage({Key? key}) : super(key: key);

  @override
  State<MyPage> createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> {

  String _titleText = "Test Title";

  final _titleFormKey = GlobalKey<FormFieldState>();

  TextEditingController _titleController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("My Page"),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            showMyModalBottomSheet();
          },
          child: Text("Show Bottom Sheet"),
        ),
      ),
    );
  }

  showMyModalBottomSheet() {
    showModalBottomSheet(
        context: context,
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(top: Radius.circular(25))),
        builder: (context) {

          return StatefulBuilder(builder: (context, setState) {
            return Container(
              padding: EdgeInsets.only(
                  bottom: MediaQuery.of(context).viewInsets.bottom),
              child: SingleChildScrollView(
                child: Container(
                  width: double.infinity,
                  child: Column(children: [
                  Container(
                    width: double.infinity,
                    margin: const EdgeInsets.only(
                        left: 10, right: 10, top: 20, bottom: 20),
                    child: Text(
                      _titleText,
                      textAlign: TextAlign.center,
                      style:
                          TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
                    ),
                  ),
                  Container(
                    width: double.infinity,
                    margin: const EdgeInsets.only(
                        left: 20, right: 20, top: 10, bottom: 10),
                    child: TextFormField(
                      key: _titleFormKey,
                      decoration: InputDecoration(labelText: "Enter Title"),
                      controller: _titleController,
                      validator: (title) {
                        if (title!.isEmpty) {
                          return "Please enter title";
                        } else {
                          return null;
                        }
                      },
                    ),
                  ),
                  Container(
                    child: ElevatedButton(
                      onPressed: () {
                        if (_titleFormKey.currentState!.validate()) {

                          updateTitle(_titleController.text.trim().toString());

                        }
                      },
                      child: Text("Update Title"),
                    ),
                  )
                ]),
              ),)
            );
          });
        });
  }

  updateTitle(String title){
    setState(() {
      _titleText = title;
    });
  }
}

The problem is that its not updating text whenever i setState using updateTitle method.问题是,每当我使用updateTitle方法设置状态时,它都不会更新文本。

updateTitle is using state class(_MyPageState) setState , that's why it is not updating. updateTitle正在使用 state class(_MyPageState) setState ,这就是它不更新的原因。 You can pass setState of StatefulBuilder while StatefulBuilder 's setState is out of scope.StatefulBuilder的 setState 超出范围时,您可以传递StatefulBuildersetState

updateTitle(
    _titleController.text.trim().toString(),
    setState);

And

  updateTitle(String title, setState) {
    setState(() {
      _titleText = title;
    });
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM