Flutter:点击时 TextFormField 重建对话框

标签 flutter

我的应用程序中有一个简单的对话框来创建用户配置文件。 它有一个可以更改的图像和一个用于输入名称的 TextFormField。 但是当我点击 TextFormField 时,它会重建对话框并重置图像变量。我该如何解决这个问题?

这是基本代码(我也遇到了此代码的问题):

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:flutter/painting.dart';
import 'dart:io';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Issue demo'),
      ),
      body: Center(
        child: RaisedButton(
          onPressed: () {
            showDialog(context: context, builder: (context) => MyDialog());
          },
          child: Text('show dialog'),
        ),
      ),
    );
  }
}

class MyDialog extends StatefulWidget {
  File image;
  String name;

  MyDialog({this.image, this.name});

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

class _MyDialogState extends State<MyDialog> {
  final _formKey = new GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return SimpleDialog(
      children: <Widget>[
        ListTile(
          leading: Icon(Icons.add_circle),
          title: Text('new person'),
        ),
        FittedBox(
          fit: BoxFit.fitWidth,
          child: FlatButton(
            shape: CircleBorder(),
            child: CircleAvatar(
                backgroundImage:
                    (widget.image != null) ? FileImage(widget.image) : null,
                child: (widget.image == null) ? Icon(Icons.person) : null),
            onPressed: () async {
              File newImage =
                  await ImagePicker.pickImage(source: ImageSource.camera);
              if (newImage != null) {
                imageCache.clear();
                setState(() {
                  widget.image = newImage;
                });
              }
            },
          ),
        ),
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Form(
            key: _formKey,
            child: TextFormField(
              initialValue: widget.name,
              maxLines: 1,
              keyboardType: TextInputType.text,
              autofocus: false,
              onSaved: (value) {
                setState(() {
                  widget.name = value;
                  print(value);
                });
              },
              decoration: new InputDecoration(
                icon: Icon(Icons.perm_identity),
                hintText: 'Name',
                contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
                border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(32.0)),
              ),
            ),
          ),
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: <Widget>[
            FlatButton(
              child: Text('Cancel'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            FlatButton(
                child: Text('Save'),
                onPressed: () {
                  Navigator.of(context).pop();
                }),
          ],
        ),
      ],
    );
  }
}

我现在已经解决了!我的答案如下,尽管我不知道为什么它解决了问题! :)

最佳答案

没关系!我已经解决了!!!!

我只是将图像变量移至 _MyDialogState,现在它可以工作了!!!! 谁能告诉我为什么它有效?

class MyDialog extends StatefulWidget {

  File image;
  String name;

  MyDialog({this.image, this.name});

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

class _MyDialogState extends State<MyDialog> {
  final _formKey = new GlobalKey<FormState>();
  String name;
  File image;

  @override
  void initState() {
    super.initState();
    image = widget.image;
    name = widget.name;
  }

  @override
  Widget build(BuildContext context) {
    return SimpleDialog(
      children: <Widget>[
        ListTile(
          leading: Icon(Icons.add_circle),
          title: Text('new person'),
        ),
        FittedBox(
          fit: BoxFit.fitWidth,
          child: FlatButton(
            shape: CircleBorder(),
            child: CircleAvatar(
                backgroundImage:
                    (image != null) ? FileImage(image) : null,
                child: (image == null) ? Icon(Icons.person) : null),
            onPressed: () async {
              File newImage =
                  await ImagePicker.pickImage(source: ImageSource.camera);
              if (newImage != null) {
                imageCache.clear();
                setState(() {
                  image = newImage;
                });
              }
            },
          ),
        ),
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Form(
            key: _formKey,
            child: TextFormField(
              initialValue: name,
              maxLines: 1,
              keyboardType: TextInputType.text,
              autofocus: false,
              onSaved: (value) {
                setState(() {
                  name = value;
                  print(value);
                });
              },
              decoration: new InputDecoration(
                icon: Icon(Icons.perm_identity),
                hintText: 'Name',
                contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
                border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(32.0)),
              ),
            ),
          ),
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: <Widget>[
            FlatButton(
              child: Text('Cancel'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            FlatButton(
                child: Text('Save'),
                onPressed: () {
                  Navigator.of(context).pop();
                }),
          ],
        ),
      ],
    );
  }
}

关于Flutter:点击时 TextFormField 重建对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57850958/

相关文章:

flutter :- Taking picture with camera

flutter - 无法通过 Flutter 中的 API 调用呈现 DropdownMenu 中的数据

flutter - 水平可滚动的标签集中在中心,并在 flutter 中捕捉

dart - 是否可以像在将颜色填充到字母表中那样以 flutter 的方式在特定图像上绘制

flutter - Flutter应用程序导航问题

flutter - 如何在 Flutter 中正确实现数学方程 (TeX)

flutter : how to left aligned a checkbox

flutter - 将抽屉项目图标更改为向右摆动

flutter - NoSuchMethodError : invalid member on null (Flutter Web)

flutter - 在 Flutter 中的 widget 前面添加 'new' 有什么意义?