SetState 不会改变颤振火力中的值

时间:2021-06-22 08:54:54

标签: firebase flutter google-cloud-firestore

  • 在 flutter 中从 firebase 获取所有文档后,我试图更新特定文档的值。
  • 当我更改值然后提交表单时,它仅采用先前的值,而不是更改后的值。
  • 'edit.dart'
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import '../events_blue_bubble_design.dart';
import '../constants.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class EditEvent extends StatefulWidget {
    final _formkey = GlobalKey<FormState>();

  final String id,
      event_amount,
      event_description,
      event_name,
      event_photo,
      event_venue;

  EditEvent(
      {this.id,
      this.event_amount,
      this.event_description,
      this.event_name,
      this.event_photo,
      this.event_venue});

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

class _EditEventState extends State<EditEvent> {
  final CollectionReference collectionUser =
      FirebaseFirestore.instance.collection('events');
  final GlobalKey<FormState> _formKey =
      GlobalKey<FormState>(); 

    // updating data in firebase
  Future updateData(BuildContext Context, event_name, id) async {
    print('event_name');
    print(event_name);
    FirebaseFirestore.instance
                .collection('events')
                .doc(id)
                .update({'event_name' : event_name});
    print("updated on firestore");
  }

  @override
  Widget build(BuildContext context) {
    final _height = MediaQuery.of(context).size.height;
    final _width = MediaQuery.of(context).size.width;
    final _formkey = GlobalKey<FormState>();
    String id = widget.id,
        name = widget.event_name,
        amount = widget.event_amount,
        desp = widget.event_description,
        venue = widget.event_venue,
        photo = widget.event_photo;
    final DateTime timestamp = DateTime.now();

        return Scaffold(
      body: SafeArea(
        child: SingleChildScrollView(
          child: Container(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Stack(
                  // circle design
                  children: <Widget>[
                    // Positioned(
                    //   child: Image.asset("assets/images/circle-design.png"),
                    // ),
                    MainPageBlueBubbleDesign(),
                  ],
                ),
                        SizedBox(height: _height * 0.015,),
                Padding(
                  padding: EdgeInsets.symmetric(
                    vertical: _height * 0.01,
                    horizontal: _width * 0.04,
                  ),
                  child: Form(
                    key: _formKey,
                    child: Column(
                      children: <Widget>[
                        // Event title
                        TextFormField(
                          initialValue: name,
                          onChanged: (value) {
                            setState(() {
                              name = value;
                            });
                          },
                          validator: (String value) {
                            if (value.isEmpty)
                              return 'Event name is required';
                            else
                              return null;
                          },
                          decoration: InputDecoration(
                            labelText: 'Event title',
                            filled: true,
                            fillColor: formFieldFillColor,
                            disabledBorder: InputBorder.none,
                            focusedBorder: InputBorder.none,
                            enabledBorder: InputBorder.none,
                            errorBorder: InputBorder.none,
                          ),
                        ),
                        SizedBox(height: _height * 0.015,),
                        Container(
                          padding: EdgeInsets.symmetric(
                            vertical: _height * 0.015,
                          ),
                          decoration: BoxDecoration(
                            gradient: LinearGradient(
                              colors: [
                                firstButtonGradientColor,
                                firstButtonGradientColor,
                                secondButtonGradientColor
                              ],
                              begin: FractionalOffset.centerLeft,
                              end: FractionalOffset.centerRight,
                            ),
                            borderRadius: BorderRadius.all(Radius.circular(15)),
                          ),
                          child: FractionallySizedBox(
                            widthFactor: 1,
                            child: TextButton(
                              child: Text(
                                'Upload',
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                  fontSize: 20,
                                  fontFamily: 'Montserrat',
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              onPressed: () async {
                                if (!_formKey.currentState.validate()) {
                                  return;
                                }
                                print("title");
                                print(name);
                                updateData(context, name, id);
                              },
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

  • 例如intialValue = Christmas Decor Workshop 并将其更改为 Christmas Decor 输出仅与初始值相同。
I/flutter (20888): title
I/flutter (20888): Christmas Decor Workshop
I/flutter (20888): event_name
I/flutter (20888): Christmas Decor Workshop
I/flutter (20888): updated on firestore

2 个答案:

答案 0 :(得分:2)

问题是因为您正在为 nameamountdespvenuephoto 和 {{1} 重新分配以前的值} 在您的 timestamp 方法中。

这意味着每次您在 buildsetState 回调中调用 TextField 时,它都会重置以下值:

onChanged

解决方案:

将变量放在您的 String id = widget.id, name = widget.event_name, amount = widget.event_amount, desp = widget.event_description, venue = widget.event_venue, photo = widget.event_photo; final DateTime timestamp = DateTime.now(); 类中,而不是在构建方法中。然后在 State 中为它们赋值。

您更新后的代码如下所示:

initState

答案 1 :(得分:1)

解决方案

  • 更改以下代码
onChanged: (value) {
  setState(() {
      name = value;
    });
},

onChanged: (value) {
name = value;
},