Flutter 常规对话框 - 设置状态不起作用

Flutter General dialog box - set state not working

我的常规对话框有问题。我想展示一颗星。然后我想在贴上星星时更改它的状态,并将图标替换为黄色星星。 但这是行不通的。对话框未刷新,因此图标未更改。拜托,你能看看下面的源代码并指出正确的方向吗? 非常感谢。


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

import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

import 'package:date_time_picker/date_time_picker.dart';



import 'package:gtd_official_sharped_focused/snackbar.dart';

String _isImportantInboxTask ;
String _isUrgentInboxTask ;

String inboxTaskDisplayed;


String isImportant = "false" ;
String isUrgent = "false" ;
String myProjectName ;

var taskSelectedID;

//---------------
//String _initialValue;


//_-----------------

var documentID;

var textController = TextEditingController();
var popUpTextController = TextEditingController();


class Inbox extends StatefulWidget {
  Inbox({Key key}) : super(key: key);
  @override
  _InboxState createState() => _InboxState();
}

class _InboxState extends State<Inbox> {
  GlobalKey<FormState> _captureFormKey = GlobalKey<FormState>();

  bool isOn = true;

  
  @override
  Widget build(BuildContext context) {
    void showAddNote() {
      TextEditingController _noteField = new TextEditingController();
      showDialog(
          context: context,
          builder: (BuildContext context) {
            return CustomAlertDialog(
              content: Container(
                width: MediaQuery.of(context).size.width / 1.3,
                height: MediaQuery.of(context).size.height / 4,
                child: Column(
                  children: [
                    TextField(
                      controller: _noteField,
                      maxLines: 4,
                      decoration: InputDecoration(
                        border: const OutlineInputBorder(
                          borderSide:
                          const BorderSide(color: Colors.black, width: 1.0),
                        ),
                      ),
                    ),
                    SizedBox(height: 10),

                    Material(
                      elevation: 5.0,
                      borderRadius: BorderRadius.circular(25.0),
                      color: Colors.white,
                      child: MaterialButton(
                        minWidth: MediaQuery.of(context).size.width / 1.5,
                        onPressed: () {
                          Navigator.of(context).pop();
                          CollectionReference users = FirebaseFirestore.instance
                              .collection('Users')
                              .doc(FirebaseAuth.instance.currentUser.uid)
                              .collection('allTasks');
                          users
                              .add({'task_Name': _noteField.text,'task_Status': 'Inbox' })
                              .then((value) => print("User Document Added"))
                              .catchError((error) =>
                              print("Failed to add user: $error"));
                        },
                        padding: EdgeInsets.fromLTRB(10.0, 15.0, 10.0, 15.0),
                        child: Text(
                          'Add Note',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            fontSize: 20.0,
                            color: Colors.black,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            );
          });
    }

    return Scaffold(
      appBar: new AppBar(
        title: new Text('Inbox Page'),
        actions: <Widget>[
          IconButton(
            icon: Icon(
              Icons.add_circle_outline,
              color: Colors.white,
            ),
            onPressed: () {
              showAddNote();
              // do something
            },
          ),
        ],
      ),

      drawer: MyMenu(),
      backgroundColor: Colors.white,
      body: Column(
        //mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            height: MediaQuery.of(context).size.height / 1.4,
            width: MediaQuery.of(context).size.width,
            child: StreamBuilder(
                stream: FirebaseFirestore.instance
                    .collection('Users')
                    .doc(FirebaseAuth.instance.currentUser.uid)
                    .collection('allTasks')
                    .where('task_Status', isEqualTo: 'Inbox')
                    .snapshots(),
                builder: (BuildContext context,
                    AsyncSnapshot<QuerySnapshot> snapshot) {
                  if (!snapshot.hasData) {
                    return Center(
                      child: CircularProgressIndicator(),
                    );
                  }

                  return ListView(
                    children: snapshot.data.docs.map((document) {
                      return Wrap(
                          children: [Card(
                            child: SwipeActionCell(
                              key: ObjectKey(document.data()['task_Name']),
                              actions: <SwipeAction>[
                                SwipeAction(
                                    title: "delete",
                                    onTap: (CompletionHandler handler) {
                                      CollectionReference users = FirebaseFirestore
                                          .instance
                                          .collection('Users')
                                          .doc(
                                          FirebaseAuth.instance.currentUser.uid)
                                          .collection('allTasks');
                                      users
                                          .doc(document.id)
                                          .delete()
                                          .then((value) => print("Note Deleted"))
                                          .catchError((error) => print(
                                          "Failed to delete Task: $error"));
                                    },
                                    color: Colors.red),
                              ],

                              child: Padding(
                                padding: const EdgeInsets.all(0.0),
                                child: ListTile(
                                  leading: ConstrainedBox(
                                    constraints: BoxConstraints(
                                      minWidth: leadingIconMinSize,
                                      minHeight: leadingIconMinSize,
                                      maxWidth: leadingIconMaxSize,
                                      maxHeight: leadingIconMaxSize,
                                    ),
                                    child: Image.asset('assets/icons/inbox.png'),
                                  ),

                                  title: GestureDetector(
                                    child: Text(
                                      //'task_Name' correspond au nom du champ dans la table
                                      document.data()['task_Name'],
                                      maxLines: 2,
                                      overflow: TextOverflow.ellipsis,
                                    ),

                                    // Pour editer task
                                    onDoubleTap: (){
                                      taskSelectedID =  FirebaseFirestore
                                          .instance
                                          .collection('Users')
                                          .doc(
                                          FirebaseAuth.instance.currentUser.uid)
                                          .collection('allTasks')
                                          .doc(document.id);

                                      //Dialog

                                      return  showGeneralDialog(
                                          context: context,
                                          barrierDismissible: true,
                                          barrierLabel: MaterialLocalizations.of(context)
                                              .modalBarrierDismissLabel,
                                          barrierColor: Colors.black45,
                                          transitionDuration: const Duration(milliseconds: 20),
                                          pageBuilder: (BuildContext buildContext,
                                              Animation animation,
                                              Animation secondaryAnimation) {
                                            return Scaffold(
                                              appBar: AppBar(
                                                title: Text ('Edit Task'),
                                                leading: InkWell(
                                                    child: Icon(Icons.close),
                                                    onTap:(){Navigator.of(context).pop();}
                                                ),
                                                actions: [Padding(
                                                  padding: const EdgeInsets.fromLTRB(0, 0,16.0,0),
                                                  child: InkWell(
                                                      child: Icon(Icons.save),
                                                      onTap: () {
                                                        final loFormInbox = _captureFormKey
                                                            .currentState;
                                                        if (loFormInbox.validate()) {
                                                          loFormInbox.save();
                                                          
                                                          CollectionReference users = FirebaseFirestore
                                                              .instance
                                                              .collection(
                                                              'Users')
                                                              .doc(FirebaseAuth
                                                              .instance
                                                              .currentUser.uid)
                                                              .collection(
                                                              'allTasks');
                                                          users
                                                              .add({
                                                            'task_Name': _valueTaskNameSaved,

                                                          })
                                                              .then((value) =>
                                                              print(
                                                                  "Task Created"))
                                                              .catchError((
                                                              error) =>
                                                              print(
                                                                  "Failed to add task: $error"));
                                                          

                                                          showSimpleFlushbar(
                                                              context,
                                                              'Task Saved',
                                                              _valueTaskNameSaved,
                                                              Icons
                                                                  .mode_comment);
                                                          loFormInbox.reset();
                                                          isImportant = 'false';
                                                          isUrgent = 'false';
                                                        }
                                                      }
                                                  ),
                                                )],
                                              ),
                                              body: Center(
                                                child: Container(
                                                  width: MediaQuery.of(context).size.width - 10,
                                                  height: MediaQuery.of(context).size.height -  80,
                                                  padding: EdgeInsets.all(20),
                                                  color: Colors.white,
                                                  child: Column(
                                                    children: [

                                                      Theme(
                                                          data: ThemeData(
                                                              inputDecorationTheme: InputDecorationTheme(
                                                                border: InputBorder.none,
                                                              )
                                                          ),
                                                          child: Padding(
                                                            padding: const EdgeInsets.fromLTRB(8.0, 0.0, 15.0, 1.0),
                                                            child: TextFormField(

                                                              initialValue: document.data()['task_Name'],
                                                              decoration: InputDecoration(hintText: "Task Name"),
                                                              maxLength: 70,
                                                              maxLines: 2,
                                                              onChanged: (valProjectName) => setState(() => _valueTaskNameChanged = valProjectName),
                                                              validator: (valProjectName) {
                                                                setState(() => _valueTaskNameToValidate = valProjectName);
                                                                return valProjectName.isEmpty? "Task name cannot be empty" : null;
                                                              },
                                                              onSaved: (valProjectName) => setState(() => _valueTaskNameSaved = valProjectName),
                                                            ),
                                                          )),

                                                      //Test Energy et Time / Important /urgent
                                                      Material(
                                                          child:
                                                          Container(
                                                            // color: Colors.red,
                                                            alignment: Alignment.center,
                                                            child: Row(
                                                              mainAxisAlignment: MainAxisAlignment.center,
                                                              children:[
                                                                
                                                                //Important
                                                                FlatButton(
                                                                  child:
                                                                  InkWell(
                                                                    child: Container(
                                                                      //   color: Colors.white,
                                                                        child: Column(
                                                                          mainAxisAlignment: MainAxisAlignment.center,
                                                                          children: [
                                                                            isImportant =="true" ? Icon(Icons.star,color: Colors.orange,) :
                                                                            Icon(Icons.star_border, color: Colors.grey,),
                                                                            // Icon(Icons.battery_charging_full),
                                                                            Text('Important'),
                                                                          ],
                                                                        )
                                                                    ),
                                                                    onTap: () {
                                                                      setState(() {
                                                                        if (isImportant=='true'){
                                                                          isImportant = 'false';}
                                                                        else
                                                                        {isImportant= 'true';
                                                                        }
                                                                      });
                                                                    },
                                                                  ),
                                                                ),


                                                      RaisedButton(
                                                        onPressed: () {
                                                          Navigator.of(context).pop();
                                                        },
                                                        child: Text(
                                                          "Close",
                                                          style: TextStyle(color: Colors.white),
                                                        ),
                                                        color: const Color(0xFF1BC0C5),
                                                      )

                                                      //++++++++++++++++
                                                    ],
                                                  ),
                                                ),
                                              ),
                                            );
                                          });

                                    },

                                  ),
                                  ),
                                ),
                              ),
                            ),
                          ),
                          ]
                      );
                    }).toList(),
                  );
                }),
          ),
        ],
      ),
      bottomNavigationBar:  MyBottomAppBar(),  //PersistentBottomNavBar(),
    );
  }


}

  @override
  Widget build(BuildContext context){
    return _widget();
  }
}



感谢您的解决方案,我能够做我想做的事。但是现在,我有另一个问题。在我的代码版本 1 中,我使用的是这段代码

Theme(
                                                          data: ThemeData(
                                                              inputDecorationTheme: InputDecorationTheme(
                                                                border: InputBorder.none,
                                                              )
                                                          ),
                                                          child: Padding(
                                                            padding: const EdgeInsets.fromLTRB(8.0, 0.0, 15.0, 1.0),
                                                            child: TextFormField(

                                                              initialValue: document.data()['task_Name'],
                                                              decoration: InputDecoration(hintText: "Task Name"),
                                                              maxLength: 70,
                                                              maxLines: 2,
                                                              onChanged: (valProjectName) => setState(() => _valueTaskNameChanged = valProjectName),
                                                              validator: (valProjectName) {
                                                                setState(() => _valueTaskNameToValidate = valProjectName);
                                                                return valProjectName.isEmpty? "Task name cannot be empty" : null;
                                                              },
                                                              onSaved: (valProjectName) => setState(() => _valueTaskNameSaved = valProjectName),
                                                            ),
                                                          )),

这部分效果很好。但是在修改之后,我得到了一个错误。错误与文档有关。

未定义的名称'document'。尝试将名称更正为已定义的名称,或定义名称。

拜托,你能帮助我完成这个页面吗?谢谢

我会建议你使用这个包,它很棒 flutter_rating_bar

如果这不能满足您的需求,请随时发表评论

所以你想改变对话框中点击图标的颜色, 但不幸的是,您在 showGeneralDialog builder 的 return 中使用无状态小部件 Scaffold,所以可能有帮助的一件事是制作一个单独的 StateFull Widget RatingDialogBox 并在生成器中使用它。

您还可以使用 IconButton

而不是 InkWell