Флаттер: список плиток не удаляется в List View Builder, но удаляется из базы данных после считывания - PullRequest
0 голосов
/ 19 марта 2020

enter image description here

Я извлекаю все эти болезни из Firebase, в построителе представления списка, используя Future Builder. Для построителя представления списка я использовал следующие плитки: Пользовательские плитки и код указан.

Теперь, если я хочу удалить плитку Testing , тогда это произошло , Когда я пролистываю плитку, она удаляется из Firebase , но все равно показывается здесь в построителе представления списка. Как я могу удалить его из этого списка?

Но если я перезагрузлю эту страницу, это означает, что если я открою другой экран и вернусь к этому экрану, то эта плитка исчезнет, ​​потому что Future Builder перезагрузка страницы.

Вот мой код этой Панели врача Класс

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:medkit/doctor/addDisease.dart';
import 'package:medkit/doctor/doctorProfile.dart';
import 'package:medkit/otherWidgetsAndScreen/customListTiles.dart';
import '../animations/bottomAnimation.dart';
import 'doctorLogin.dart';

class DoctorPanel extends StatefulWidget {
  final DoctorDetails detailsUser;

  DoctorPanel({Key key, @required this.detailsUser}) : super(key: key);

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

class _DoctorPanelState extends State<DoctorPanel> {
  Future getDiseaseInfo() async {
    var firestore = Firestore.instance;
    QuerySnapshot qn = await firestore.collection("Diseases").getDocuments();
    return qn.documents;
  }

  final GoogleSignIn _gSignIn = GoogleSignIn();

  bool editPanel = false;

  Future<bool> _onWillPop() async {
    return (await showDialog(
          context: context,
          builder: (context) => new AlertDialog(
            title: new Text(
              "Log Out",
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
            content: new Text("Are You Sure?"),
            actions: <Widget>[
              // usually buttons at the bottom of the dialog
              new RaisedButton(
                shape: StadiumBorder(),
                color: Colors.white,
                child: new Text(
                  "Close",
                  style: TextStyle(color: Colors.blue),
                ),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
              new RaisedButton(
                shape: StadiumBorder(),
                color: Colors.white,
                child: new Text(
                  "Log Out",
                  style: TextStyle(color: Colors.red),
                ),
                onPressed: () {
                  _gSignIn.signOut();
                  int count = 0;
                  Navigator.of(context).popUntil((_) => count++ >= 2);
                },
              ),
            ],
          ),
        )) ??
        false;
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
          body: Stack(
        children: <Widget>[
          Positioned(
              top: ScreenUtil.instance.setWidth(50),
              right: ScreenUtil.instance.setWidth(-20),
              child: Image(
                  height: ScreenUtil.instance.setHeight(200),
                  image: AssetImage('assets/bigDoc.png'))),
          Container(
            margin:
                EdgeInsets.fromLTRB(0, ScreenUtil.instance.setHeight(50), 0, 0),
            child: Hero(
              tag: 'docPic',
              child: FlatButton(
                  shape: CircleBorder(),
                  onPressed: () => Navigator.push(
                      context,
                      new MaterialPageRoute(
                          builder: (context) => DoctorProfile(
                              doctorDetails: widget.detailsUser))),
                  child: CircleAvatar(
                      backgroundColor: Colors.black.withOpacity(0.2),
                      backgroundImage:
                          NetworkImage(widget.detailsUser.photoUrl))),
            ),
          ),
          Positioned(
            top: ScreenUtil.instance.setHeight(210),
            left: ScreenUtil.instance.setWidth(20),
            child: editPanel
                ? Container(
                    height: ScreenUtil.instance.setHeight(35),
                    child: WidgetAnimator(
                      RawMaterialButton(
                        shape: StadiumBorder(),
                        fillColor: Colors.blue,
                        child: Text(
                          'Add More',
                          style: TextStyle(color: Colors.white),
                        ),
                        onPressed: () {
                          Navigator.push(
                              context,
                              new MaterialPageRoute(
                                  builder: (context) => AddDisease(
                                        doctorName: widget.detailsUser.userName,
                                      )));
                        },
                      ),
                    ),
                  )
                : Text(''),
          ),
          Container(
            margin: EdgeInsets.fromLTRB(ScreenUtil.instance.setWidth(20),
                ScreenUtil.instance.setHeight(155), 0, 0),
            child: Row(
              children: <Widget>[
                Container(
                  height: ScreenUtil.instance.setHeight(35),
                  child: FloatingActionButton(
                    heroTag: 'editBtn',
                    tooltip: 'Edit Panel',
                    backgroundColor: editPanel ? Colors.green : Colors.white,
                    child: editPanel
                        ? WidgetAnimator(
                            Icon(
                              Icons.done,
                              size: ScreenUtil.instance.setHeight(25),
                              color: Colors.white,
                            ),
                          )
                        : WidgetAnimator(
                            Icon(
                              Icons.edit,
                              color: Colors.black,
                              size: ScreenUtil.instance.setHeight(25),
                            ),
                          ),
                    onPressed: () {
                      setState(() {
                        editPanel = !editPanel;
                      });
                    },
                  ),
                ),
                SizedBox(
                  width: ScreenUtil.instance.setWidth(4),
                ),
                Text(
                  "Doctor's",
                  style: GoogleFonts.abel(
                      fontSize: ScreenUtil.instance.setSp(34),
                      fontWeight: FontWeight.bold),
                ),
              ],
            ),
          ),
          Positioned(
              top: ScreenUtil.instance.setHeight(190),
              left: ScreenUtil.instance.setWidth(120),
              child: Text(
                'Panel',
                style: TextStyle(fontSize: ScreenUtil.instance.setSp(20)),
              )),
          FutureBuilder(
            future: getDiseaseInfo(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return Center(
                  child: CircularProgressIndicator(
                    valueColor: new AlwaysStoppedAnimation<Color>(Colors.black),
                  ),
                );
              } else {
                return Container(
                  margin: EdgeInsets.fromLTRB(
                      0, ScreenUtil.instance.setHeight(255), 0, 0),
                  child: ListView.separated(
                    padding: EdgeInsets.symmetric(
                        horizontal: ScreenUtil.instance.setWidth(12),
                        vertical: ScreenUtil.instance.setHeight(15)),
                    separatorBuilder: (context, index) => Divider(
                      color: Colors.transparent,
                    ),
                    itemCount: snapshot.data.length,
                    itemBuilder: (context, index) {
                      return WidgetAnimator(CustomTile(
                        listLength: snapshot.data.length,
                        itemIndex: index,
                        delBtn: editPanel,
                        snapshot: snapshot.data[index],
                      ));
                    },
                  ),
                );
              }
            },
          )
        ],
      )),
    );
  }
}

Плитка Custom List Код класса

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:medkit/otherWidgetsAndScreen/medDetails.dart';
import 'package:toast/toast.dart';

class CustomTile extends StatefulWidget {
  final int itemIndex;
  final bool delBtn;
  final DocumentSnapshot snapshot;
  final int listLength;

  CustomTile({this.listLength, this.itemIndex, this.delBtn, this.snapshot});

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

class _CustomTileState extends State<CustomTile> {
  @override
  Widget build(BuildContext context) {
    return Dismissible(
      key: UniqueKey(),
      onDismissed: (direction) {
        setState(() {
          Firestore.instance
              .collection('Diseases')
              .document(widget.snapshot.data['disName'])
              .delete();
          Toast.show('Deleted Successfully!', context, backgroundColor: Colors.red, duration: Toast.LENGTH_LONG);
        });
      },
      child: GestureDetector(
        onTap: () {
          Navigator.push(
              context,
              new MaterialPageRoute(
                  builder: (context) => MedDetails(
                        snapshot: widget.snapshot,
                      )));
        },
        child: Container(
          padding: EdgeInsets.symmetric(vertical: 8.0, horizontal: 12.0),
          height: 80,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(8)),
            gradient: new LinearGradient(colors: [
              Colors.white.withOpacity(0.8),
              !widget.delBtn
                  ? Colors.blueGrey.withOpacity(0.2)
                  : Colors.redAccent.withOpacity(0.2),
            ]),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Text(
                widget.snapshot.data['disName'],
                style: GoogleFonts.lato(fontSize: 25, letterSpacing: 2),
              ),
              Container(
                height: 35,
                child: FlatButton(
                  onPressed: () {
                    widget.delBtn
                        ? Firestore.instance
                            .collection('Diseases')
                            .document(widget.snapshot.data['disName'])
                            .delete()
                        : Navigator.push(
                            context,
                            new MaterialPageRoute(
                                builder: (context) => MedDetails(
                                      snapshot: widget.snapshot,
                                    )));
                  },
                  shape: StadiumBorder(),
                  child: widget.delBtn
                      ? Icon(
                          Icons.delete,
                          color: Colors.red,
                          size: 30,
                        )
                      : Icon(
                          Icons.arrow_forward_ios,
                          color: Colors.black,
                          size: 20,
                        ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
...