AlertDialog 中的 TextFormField 模糊文本不会改变

发布于 2025-01-15 18:22:55 字数 5569 浏览 1 评论 0原文

我想更改 AlertDialog 中 TextFormField 的模糊文本模式,但它不起作用

单击 IconButton 不会改变 AlertDialog 中的obscureText 为 TextFormField

我想更改 AlertDialog 中 TextFormField 的obscureText 模式,但它不起作用

单击 IconButton 不会更改 AlertDialog 中的 obliqueText 到 TextFormField

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

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final username = TextEditingController(text: '');
  final password = TextEditingController(text: '');
  final formKey = GlobalKey<FormState>();
  late bool obscure;

  @override
  void initState() {
    obscure = true;
    super.initState();
  }

  @override
  void dispose() {
    username.dispose();
    password.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        actions: <Widget>[
          IconButton(
            onPressed: () {
              showDialog(
                  context: context,
                  barrierDismissible: false,
                  builder: (_) {
                    return AlertDialog(
                      title: const Text('Connection'),
                      content: SizedBox(
                          height: 400,
                          width: 400,
                          child: Form(
                            key: formKey,
                            child: Column(
                              children: <Widget>[
                                TextFormField(
                                  cursorColor: Colors.grey,
                                  textInputAction: TextInputAction.next,
                                  maxLines: 1,
                                  controller: username,
                                  validator: (value) {
                                    return null;
                                  },
                                  decoration: const InputDecoration(
                                    isDense: true,
                                    prefixIcon: Icon(
                                      Icons.person_outlined,
                                    ),
                                    labelText: 'username',
                                  ),
                                ),
                                const SizedBox(
                                  height: 20.0,
                                ),
                                TextFormField(
                                  cursorColor: Colors.grey,
                                  controller: password,
                                  textInputAction: TextInputAction.next,
                                  decoration: InputDecoration(
                                    isDense: true,
                                    prefixIcon: const Icon(Icons.key),
                                    labelText: 'password',
                                    suffixIcon: IconButton(
                                        icon: const Icon(
                                            Icons.remove_red_eye_outlined),
                                        onPressed: () {
                                          // CHAGE OBSCURE
                                          setState(() {
                                            obscure = !obscure;
                                            if (kDebugMode) {
                                              print(obscure); // OK
                                            }
                                          });
                                        }),
                                  ),
                                  obscureText: obscure, // NOT OK
                                  obscuringCharacter: '*',
                                  validator: (String? value) {
                                    return null;
                                  },
                                ),
                              ],
                            ),
                          )),
                      actions: [
                        TextButton(
                          child: const Text('Send'),
                          onPressed: () {
                            if (formKey.currentState!.validate()) {
                              Navigator.of(context).pop();
                            }
                          },
                        ),
                      ],
                    );
                  });
            },
            icon: const Icon(Icons.person_outline_outlined),
          ),
        ],
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: const <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
          ],
        ),
      ),
    );
  }
}

I want to change the obscureText mode of a TextFormField in an AlertDialog but it doesn't work

Clicking the IconButton does not change
the obscureText to TextFormField in AlertDialog

I want to change the obscureText mode of a TextFormField in an AlertDialog but it doesn't work

Clicking the IconButton does not change
the obscureText to TextFormField in AlertDialog

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

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final username = TextEditingController(text: '');
  final password = TextEditingController(text: '');
  final formKey = GlobalKey<FormState>();
  late bool obscure;

  @override
  void initState() {
    obscure = true;
    super.initState();
  }

  @override
  void dispose() {
    username.dispose();
    password.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        actions: <Widget>[
          IconButton(
            onPressed: () {
              showDialog(
                  context: context,
                  barrierDismissible: false,
                  builder: (_) {
                    return AlertDialog(
                      title: const Text('Connection'),
                      content: SizedBox(
                          height: 400,
                          width: 400,
                          child: Form(
                            key: formKey,
                            child: Column(
                              children: <Widget>[
                                TextFormField(
                                  cursorColor: Colors.grey,
                                  textInputAction: TextInputAction.next,
                                  maxLines: 1,
                                  controller: username,
                                  validator: (value) {
                                    return null;
                                  },
                                  decoration: const InputDecoration(
                                    isDense: true,
                                    prefixIcon: Icon(
                                      Icons.person_outlined,
                                    ),
                                    labelText: 'username',
                                  ),
                                ),
                                const SizedBox(
                                  height: 20.0,
                                ),
                                TextFormField(
                                  cursorColor: Colors.grey,
                                  controller: password,
                                  textInputAction: TextInputAction.next,
                                  decoration: InputDecoration(
                                    isDense: true,
                                    prefixIcon: const Icon(Icons.key),
                                    labelText: 'password',
                                    suffixIcon: IconButton(
                                        icon: const Icon(
                                            Icons.remove_red_eye_outlined),
                                        onPressed: () {
                                          // CHAGE OBSCURE
                                          setState(() {
                                            obscure = !obscure;
                                            if (kDebugMode) {
                                              print(obscure); // OK
                                            }
                                          });
                                        }),
                                  ),
                                  obscureText: obscure, // NOT OK
                                  obscuringCharacter: '*',
                                  validator: (String? value) {
                                    return null;
                                  },
                                ),
                              ],
                            ),
                          )),
                      actions: [
                        TextButton(
                          child: const Text('Send'),
                          onPressed: () {
                            if (formKey.currentState!.validate()) {
                              Navigator.of(context).pop();
                            }
                          },
                        ),
                      ],
                    );
                  });
            },
            icon: const Icon(Icons.person_outline_outlined),
          ),
        ],
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: const <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
          ],
        ),
      ),
    );
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

腹黑女流氓 2025-01-22 18:22:55

为此,您必须使用 StatefulBuilder 在 Dialog 内使用 setState 并仅在其中更新 Widget。

原因:setStateAlertDialog 中具有不同的上下文,因此如果您想维护 AlertDialog 的状态,则必须使用 StatefulBuilder。它将为您的 AlertDialog

完整工作代码维护另一种状态:

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

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final username = TextEditingController(text: '');
  final password = TextEditingController(text: '');
  final formKey = GlobalKey<FormState>();
  late bool obscure;

  @override
  void initState() {
    obscure = true;
    super.initState();
  }

  @override
  void dispose() {
    username.dispose();
    password.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        actions: <Widget>[
          IconButton(
            onPressed: () {
              
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (_) {
          return StatefulBuilder(
              builder: (context, setState)
          {
            return AlertDialog(
              title: const Text('Connection'),
              content: SizedBox(
                  height: 400,
                  width: 400,
                  child: Form(
                    key: formKey,
                    child: Column(
                      children: <Widget>[
                        TextFormField(
                          cursorColor: Colors.grey,
                          textInputAction: TextInputAction.next,
                          maxLines: 1,
                          controller: username,
                          validator: (value) {
                            return null;
                          },
                          decoration: const InputDecoration(
                            isDense: true,
                            prefixIcon: Icon(
                              Icons.person_outlined,
                            ),
                            labelText: 'username',
                          ),
                        ),
                        const SizedBox(
                          height: 20.0,
                        ),
                        TextFormField(
                          cursorColor: Colors.grey,
                          controller: password,
                          textInputAction: TextInputAction.next,
                          decoration: InputDecoration(
                            isDense: true,
                            prefixIcon: const Icon(Icons.key),
                            labelText: 'password',
                            suffixIcon: IconButton(
                                icon: const Icon(Icons.remove_red_eye_outlined),
                                onPressed: () {
                                  // CHAGE OBSCURE
                                  setState(() {
                                    obscure = !obscure;
                                    if (kDebugMode) {
                                      print(obscure); // OK
                                    }
                                  });
                                }),
                          ),
                          obscureText: obscure,
                          // NOT OK
                          obscuringCharacter: '*',
                          validator: (String? value) {
                            return null;
                          },
                        ),
                      ],
                    ),
                  )),
              actions: [
                TextButton(
                  child: const Text('Send'),
                  onPressed: () {
                    if (formKey.currentState!.validate()) {
                      Navigator.of(context).pop();
                    }
                  },
                ),
              ],
            );
          });
        });

            },
            icon: const Icon(Icons.person_outline_outlined),
          ),
        ],
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: const <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
          ],
        ),
      ),
    );
  }
}

For that you have to use StatefulBuilder to use setState inside Dialog and update Widgets only inside of it.

Reason: setState is having different context inside the AlertDialog, so If you want to maintain the state of AlertDialog you must have to use StatefulBuilder. It will maintain another state for your AlertDialog

Full Working Code:

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

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final username = TextEditingController(text: '');
  final password = TextEditingController(text: '');
  final formKey = GlobalKey<FormState>();
  late bool obscure;

  @override
  void initState() {
    obscure = true;
    super.initState();
  }

  @override
  void dispose() {
    username.dispose();
    password.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        actions: <Widget>[
          IconButton(
            onPressed: () {
              
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (_) {
          return StatefulBuilder(
              builder: (context, setState)
          {
            return AlertDialog(
              title: const Text('Connection'),
              content: SizedBox(
                  height: 400,
                  width: 400,
                  child: Form(
                    key: formKey,
                    child: Column(
                      children: <Widget>[
                        TextFormField(
                          cursorColor: Colors.grey,
                          textInputAction: TextInputAction.next,
                          maxLines: 1,
                          controller: username,
                          validator: (value) {
                            return null;
                          },
                          decoration: const InputDecoration(
                            isDense: true,
                            prefixIcon: Icon(
                              Icons.person_outlined,
                            ),
                            labelText: 'username',
                          ),
                        ),
                        const SizedBox(
                          height: 20.0,
                        ),
                        TextFormField(
                          cursorColor: Colors.grey,
                          controller: password,
                          textInputAction: TextInputAction.next,
                          decoration: InputDecoration(
                            isDense: true,
                            prefixIcon: const Icon(Icons.key),
                            labelText: 'password',
                            suffixIcon: IconButton(
                                icon: const Icon(Icons.remove_red_eye_outlined),
                                onPressed: () {
                                  // CHAGE OBSCURE
                                  setState(() {
                                    obscure = !obscure;
                                    if (kDebugMode) {
                                      print(obscure); // OK
                                    }
                                  });
                                }),
                          ),
                          obscureText: obscure,
                          // NOT OK
                          obscuringCharacter: '*',
                          validator: (String? value) {
                            return null;
                          },
                        ),
                      ],
                    ),
                  )),
              actions: [
                TextButton(
                  child: const Text('Send'),
                  onPressed: () {
                    if (formKey.currentState!.validate()) {
                      Navigator.of(context).pop();
                    }
                  },
                ),
              ],
            );
          });
        });

            },
            icon: const Icon(Icons.person_outline_outlined),
          ),
        ],
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: const <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
          ],
        ),
      ),
    );
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文