dart - Flutter setState 正在恢复

标签 dart flutter setstate

当我 setState 并将图像添加到 _images 数组时,它似乎已经添加,但很快又恢复了:

enter image description here

此表格松散地遵循 Brian Egan's redux architecture example :

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

class Note {
  final String comments;
  final List<String> images;

  Note({
    this.comments,
    this.images,
  });
}

class AddNote extends StatefulWidget {
  final Note note;
  final bool isEditing;

  AddNote({
    this.note,
    this.isEditing,
  });

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

class _AddNoteState extends State<AddNote> {
  static final _scaffoldKey = GlobalKey<ScaffoldState>();
  static final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  List<String> _images;
  String _comments;

  Note get _note => widget.note;
  bool get _isEditing => widget.isEditing;

  @override
  Widget build(BuildContext context) {
    _images = _note.images;
    _comments = _note.comments;

    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: Text(
          _isEditing ? "Edit Note" : "Create Note",
        ),
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            children: [
              _photoPickerField(),
              _notesField(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _photoPickerField() {
    return GestureDetector(
      onTap: _selectPicture,
      child: Row(
        children: <Widget>[
          Container(
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey, width: 1,),
              borderRadius: BorderRadius.all(const Radius.circular(10)),
            ),
            child: SizedBox(child: Icon(Icons.camera_alt), width: 110, height: 110,)
          ),
        ] + _imagesRowItems(),
      ),
    );
  }

  List<Widget> _imagesRowItems() {
    return _images.map((image) {
      return SizedBox(
        height: 110,
        width: 110,
        child: Image.file(File(image), height: 110, width: 110, fit: BoxFit.cover),
      );
    }).toList();
  }

  Future _selectPicture() async {
    return ImagePicker.pickImage(source: ImageSource.gallery)
      .then((file) {
        setState(() {
          _images.add(file.path);
        });
    });
  }

  Widget _notesField() {
    return TextFormField(
      maxLines: 2,
      keyboardType: TextInputType.multiline,
      initialValue: _comments,
      onSaved: (String value) => _comments = value,
    );
  }
}

请注意,评论字段保持其状态没有问题。如何以保持其新状态的方式添加到图像数组?

最佳答案

您的问题是您在 Widget 状态的 build() 方法中设置变量,但是每次调用 setState() 时都会调用 build 方法因为你的变量已经改变,所以它会重置图像和评论。

要修复它,您应该在 initState() 方法中初始化您的变量,如下所示:

class _AddNoteState extends State<AddNote> {
  ...
  @override
  void initState() {
    super.initState();
    _images = _note.images;
    _comments = _note.comments;
  }
}

并从 build() 方法中移除它们。

关于dart - Flutter setState 正在恢复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54694435/

相关文章:

java - flutter doctor --android-licenses 给出了一个java错误

android - 在 VS Code 上模拟 Android 时为 "Invalid Argument(s): Cannot find executable for null"- Mac OS X

javascript - React setState 不会在 ajax 成功时重新渲染

javascript - 使用 parseFloat 时,React onChange 正在吞下我的小数点

reactjs - 如何为初始化数组中的每个项目设置键名称

http - 如何使用http上传图片?

android - 未检测到键盘。 MediaQuery.of(context).viewInsets.bottom 始终返回 0.0

flutter - 未处理的异常 : Content size below specified contentLength. 已写入 206 字节但预期为 375482。#228

flutter - 长按显示对话框,手指向上弹出

xcode - 为什么我收到此错误无法为模拟器构建应用程序。在 iPhone 11 Pro Max 上启动应用程序时出错?