簡體   English   中英

Flutter - 為什么 setstate 在彈出窗口中不起作用?

[英]Flutter - Why setstate doesn't work on popup?

我想通過用戶交互更改彈出窗口上的文本,但它沒有改變。 我試過 navigator.pop(context) 並重新啟動 show 方法。 它可以正常工作,但它是正確的方法嗎? 我可以在沒有 Navigator.pop 的情況下更改彈出窗口的值嗎? 為什么它不起作用?

這是我的代碼。

import 'package:flutter/material.dart';
import 'package:rflutter_alert/rflutter_alert.dart';

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

class RatelApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: Text('RFlutter Alert by Ratel'),
        ),
        body: Home(),
      ),
    );
  }
}



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

class _HomeState extends State<Home> {
  String val = "Deneme";
  showAlertDialog(BuildContext context, Function onPressed) {
    // set up the button
    Widget okButton = FlatButton(
      child: Text(val),
      onPressed: onPressed,
    );

    // set up the AlertDialog
    AlertDialog alert = AlertDialog(
      title: Text("My title"),
      content: Text("This is my message."),
      actions: [
        okButton,
      ],
    );

    // show the dialog
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return alert;
      },
    );
  }
  @override
  Widget build(BuildContext context) {
    return Container(
      child: RaisedButton(
        child: Text("Show Popup"),
        onPressed: () {
          showAlertDialog(context, (){
            setState(() {
              val = "changed";

            });
          });
        },

      ),
    );
  }
}

對話框通常是無狀態的,也不是調用Widget的 state 的一部分,因此調用setState方法對對話框沒有任何作用。 要制作一個可以更改內容的對話框,請使用StatefulBuilder

文檔有一個示例,展示了如何在對話框中使用它,就像在您的應用程序中一樣。

文檔示例:

await showDialog<void>(
  context: context,
  builder: (BuildContext context) {
    int selectedRadio = 0;
    return AlertDialog(
      content: StatefulBuilder(
        builder: (BuildContext context, StateSetter setState) {
          return Column(
            mainAxisSize: MainAxisSize.min,
            children: List<Widget>.generate(4, (int index) {
              return Radio<int>(
                value: index,
                groupValue: selectedRadio,
                onChanged: (int value) {
                  setState(() => selectedRadio = value);
                },
              );
            }),
          );
        },
      ),
    );
  },
);

您需要使用 StatefulBuilder 小部件包裝您的 AlertDialog。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM