扑向溪流构造者陷入了状态,等待重新宣扬回到页面

发布于 2025-02-09 23:34:37 字数 11759 浏览 2 评论 0原文

我是Flutter的新手,我对StreamBuilder有问题。启动时,返回了来自Firestore的快照,但是当我导航到另一个页面时,然后返回页面时,快照的连接状态被卡在等待中。当热重新加载或刷新页面时,显示数据并正常工作。该问题仅在重新散布回页面时才发生。我认为,由于它不会添加新数据或编辑数据,因此StreamBuilder不会更新且不会重建。

初始streambuilder

重新恢复后

我还使用dataTable在表格中显示我的数据,以下代码可能会有点长。

return StreamBuilder<QuerySnapshot>(
    stream: providerDBsnaps,
    builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
      switch (snapshot.connectionState) {
        case ConnectionState.none:
          return const Text('Something went wrong');
        case ConnectionState.waiting:
          return const LinearProgressIndicator();
        case ConnectionState.active:
          if (snapshot.hasData) {
            final List<DocumentSnapshot> documents = snapshot.data!.docs;

            providers = documents
                .map((e) =>
                    ProviderList.fromMap(e.data() as Map<String, dynamic>))
                .toList();

            List<DataRow> providerListItems() {
              List<DataRow> providerList = [];
              for (var i = 0; i < providers.length; i++) {
                bool status = providers[i].status;
                DataRow dataRow =
                    DataRow(onSelectChanged: (bool? newVal) {}, cells: [
                  DataCell(Container(
                    width: 30,
                    child: Text((i + 1).toString()),
                  )),
                  DataCell(Container(
                    width: 120,
                    child: Text(providers[i].name),
                  )),
                  DataCell(Container(
                    width: 200,
                    child: Text(providers[i].address),
                  )),
                  DataCell(
                    Container(
                        width: 120, child: Text(providers[i].contact)),
                  ),
                  DataCell(
                    Container(width: 100, child: Text(providers[i].phone)),
                  ),
                  DataCell(
                    MouseRegion(
                      cursor: SystemMouseCursors.click,
                      child: Container(
                        alignment: Alignment.center,
                        width: 42,
                        height: 22,
                        child: FlutterSwitch(
                          value: providers[i].status,
                          width: 40.0,
                          height: 20.0,
                          borderRadius: 30.0,
                          onToggle: (val) {
                            setState(() {
                              showDialog(
                                  context: context,
                                  builder: (context) => AlertDialog(
                                        title: const CustomText(
                                          text: "Warning",
                                          weight: FontWeight.bold,
                                          size: 22,
                                        ),
                                        content: const CustomText(
                                          text:
                                              "Are you sure you want to change the status?",
                                          size: 16,
                                        ),
                                        actions: [
                                          TextButton(
                                            onPressed: () {
                                              status = val;
                                              providerDB
                                                  .doc(providers[i].id)
                                                  .update(
                                                      {'p_status': status});
                                              Navigator.pop(context);
                                            },
                                            child: const CustomText(
                                                text: 'Yes'),
                                          ),
                                          TextButton(
                                            onPressed: () {
                                              Navigator.pop(context);
                                            },
                                            child: const CustomText(
                                                text: 'No'),
                                          )
                                        ],
                                      ));
                            });
                          },
                        ),
                      ),
                    ),
                  ),
                  DataCell(Row(
                    children: [
                      SizedBox(
                        width: 30,
                        child: MaterialButton(
                          padding: const EdgeInsets.all(7.0),
                          onPressed: () {
                            menuController
                                .changeActiveitemTo(EditingPageName);
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => ProviderEditPage(
                                    existing: providers[i]),
                              ),
                            );
                          },
                          child: const Icon(
                            Icons.edit,
                            color: Colors.black,
                            size: 18,
                          ),
                        ),
                      ),
                      const SizedBox(
                        width: 5,
                      ),
                      SizedBox(
                        width: 30,
                        child: MaterialButton(
                          padding: const EdgeInsets.all(7.0),
                          onPressed: () {
                            showDialog(
                                context: context,
                                builder: (context) => AlertDialog(
                                      title: const CustomText(
                                        text: "Delete Notice",
                                        weight: FontWeight.bold,
                                        size: 22,
                                      ),
                                      content: const CustomText(
                                        text:
                                            "Are you sure you want to delete the item?",
                                        size: 16,
                                      ),
                                      actions: [
                                        TextButton(
                                          onPressed: () {
                                            providerDB
                                                .doc(providers[i]
                                                    .id
                                                    .toString())
                                                .delete();
                                            Navigator.pop(context);
                                          },
                                          child:
                                              const CustomText(text: 'Yes'),
                                        ),
                                        TextButton(
                                          onPressed: () {
                                            Navigator.pop(context);
                                          },
                                          child:
                                              const CustomText(text: 'No'),
                                        )
                                      ],
                                    ));
                          },
                          child: const Icon(
                            Icons.delete,
                            color: Colors.black,
                            size: 18,
                          ),
                        ),
                      ),
                    ],
                  ))
                ]);
                providerList.add(dataRow);
              }
              return providerList;
            }

            return Container(
              height: 550,
              padding: const EdgeInsets.all(16),
              margin: const EdgeInsets.only(bottom: 30),
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(8),
                  boxShadow: [
                    BoxShadow(
                        offset: const Offset(0, 6),
                        color: lightGrey.withOpacity(.1),
                        blurRadius: 12),
                  ],
                  border: Border.all(color: lightGrey, width: .5)),
              child: DataTable(
                columnSpacing: 0,
                showCheckboxColumn: false,
                columns: const [
                  DataColumn(
                    label: CustomText(
                      text: "No.",
                      weight: FontWeight.bold,
                    ),
                  ),
                  DataColumn(
                    label: CustomText(
                      text: "Name",
                      weight: FontWeight.bold,
                    ),
                  ),
                  DataColumn(
                    label: CustomText(
                      text: "Address",
                      weight: FontWeight.bold,
                    ),
                  ),
                  DataColumn(
                    label: CustomText(
                      text: "Contact Person",
                      weight: FontWeight.bold,
                    ),
                  ),
                  DataColumn(
                    label: CustomText(
                      text: "Phone Number",
                      weight: FontWeight.bold,
                    ),
                  ),
                  DataColumn(
                    label: CustomText(
                      text: "Status",
                      weight: FontWeight.bold,
                    ),
                  ),
                  DataColumn(
                    label: CustomText(
                      text: "Tools",
                      weight: FontWeight.bold,
                    ),
                  ),
                ],
                rows: providerListItems(),
              ),
            );
          } else {
            return const Text('No data...');
          }
        case ConnectionState.done:
          return const Text('Something went wrong');
        default:
          return const Text('Something went wrong');
      }
    });

}

我做错了什么?还是一个错误?问题是否像我认为数据没有更新,因此流构建器仅构建一次?如果是这样,您可以为我提供解决方案,我似乎找不到解决方案...谢谢!

- &gt;编辑

ProviderDbsnaps的初始化

@override
void initState() {
  super.initState();
  providerDBsnaps = providerDB.snapshots();
  providerDBsnaps.listen((snapshot) {
  if (snapshot.docs.isNotEmpty) {
    final List<DocumentSnapshot> documents = snapshot.docs;

    providers = documents
        .map((e) => ProviderList.fromMap(e.data() as Map<String, dynamic>))
        .toList();
  }
});
}

I am new to flutter and I have a problem with StreamBuilder. When starting, snapshots from firestore are returned but when I navigate to another page, then return back to the page, the connection state of the snapshot is stuck in waiting. When hot reloading or refreshing the page, the data is shown and works fine. The problem only happens when re-navigating back to the page. I think that since it does not add new data or edit the data, the streambuilder will not be updated and won't rebuild.

Initial streambuilder

After re-navigating back

I also used DataTable to show my data in table form, the following code might be a little long.

return StreamBuilder<QuerySnapshot>(
    stream: providerDBsnaps,
    builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
      switch (snapshot.connectionState) {
        case ConnectionState.none:
          return const Text('Something went wrong');
        case ConnectionState.waiting:
          return const LinearProgressIndicator();
        case ConnectionState.active:
          if (snapshot.hasData) {
            final List<DocumentSnapshot> documents = snapshot.data!.docs;

            providers = documents
                .map((e) =>
                    ProviderList.fromMap(e.data() as Map<String, dynamic>))
                .toList();

            List<DataRow> providerListItems() {
              List<DataRow> providerList = [];
              for (var i = 0; i < providers.length; i++) {
                bool status = providers[i].status;
                DataRow dataRow =
                    DataRow(onSelectChanged: (bool? newVal) {}, cells: [
                  DataCell(Container(
                    width: 30,
                    child: Text((i + 1).toString()),
                  )),
                  DataCell(Container(
                    width: 120,
                    child: Text(providers[i].name),
                  )),
                  DataCell(Container(
                    width: 200,
                    child: Text(providers[i].address),
                  )),
                  DataCell(
                    Container(
                        width: 120, child: Text(providers[i].contact)),
                  ),
                  DataCell(
                    Container(width: 100, child: Text(providers[i].phone)),
                  ),
                  DataCell(
                    MouseRegion(
                      cursor: SystemMouseCursors.click,
                      child: Container(
                        alignment: Alignment.center,
                        width: 42,
                        height: 22,
                        child: FlutterSwitch(
                          value: providers[i].status,
                          width: 40.0,
                          height: 20.0,
                          borderRadius: 30.0,
                          onToggle: (val) {
                            setState(() {
                              showDialog(
                                  context: context,
                                  builder: (context) => AlertDialog(
                                        title: const CustomText(
                                          text: "Warning",
                                          weight: FontWeight.bold,
                                          size: 22,
                                        ),
                                        content: const CustomText(
                                          text:
                                              "Are you sure you want to change the status?",
                                          size: 16,
                                        ),
                                        actions: [
                                          TextButton(
                                            onPressed: () {
                                              status = val;
                                              providerDB
                                                  .doc(providers[i].id)
                                                  .update(
                                                      {'p_status': status});
                                              Navigator.pop(context);
                                            },
                                            child: const CustomText(
                                                text: 'Yes'),
                                          ),
                                          TextButton(
                                            onPressed: () {
                                              Navigator.pop(context);
                                            },
                                            child: const CustomText(
                                                text: 'No'),
                                          )
                                        ],
                                      ));
                            });
                          },
                        ),
                      ),
                    ),
                  ),
                  DataCell(Row(
                    children: [
                      SizedBox(
                        width: 30,
                        child: MaterialButton(
                          padding: const EdgeInsets.all(7.0),
                          onPressed: () {
                            menuController
                                .changeActiveitemTo(EditingPageName);
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => ProviderEditPage(
                                    existing: providers[i]),
                              ),
                            );
                          },
                          child: const Icon(
                            Icons.edit,
                            color: Colors.black,
                            size: 18,
                          ),
                        ),
                      ),
                      const SizedBox(
                        width: 5,
                      ),
                      SizedBox(
                        width: 30,
                        child: MaterialButton(
                          padding: const EdgeInsets.all(7.0),
                          onPressed: () {
                            showDialog(
                                context: context,
                                builder: (context) => AlertDialog(
                                      title: const CustomText(
                                        text: "Delete Notice",
                                        weight: FontWeight.bold,
                                        size: 22,
                                      ),
                                      content: const CustomText(
                                        text:
                                            "Are you sure you want to delete the item?",
                                        size: 16,
                                      ),
                                      actions: [
                                        TextButton(
                                          onPressed: () {
                                            providerDB
                                                .doc(providers[i]
                                                    .id
                                                    .toString())
                                                .delete();
                                            Navigator.pop(context);
                                          },
                                          child:
                                              const CustomText(text: 'Yes'),
                                        ),
                                        TextButton(
                                          onPressed: () {
                                            Navigator.pop(context);
                                          },
                                          child:
                                              const CustomText(text: 'No'),
                                        )
                                      ],
                                    ));
                          },
                          child: const Icon(
                            Icons.delete,
                            color: Colors.black,
                            size: 18,
                          ),
                        ),
                      ),
                    ],
                  ))
                ]);
                providerList.add(dataRow);
              }
              return providerList;
            }

            return Container(
              height: 550,
              padding: const EdgeInsets.all(16),
              margin: const EdgeInsets.only(bottom: 30),
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(8),
                  boxShadow: [
                    BoxShadow(
                        offset: const Offset(0, 6),
                        color: lightGrey.withOpacity(.1),
                        blurRadius: 12),
                  ],
                  border: Border.all(color: lightGrey, width: .5)),
              child: DataTable(
                columnSpacing: 0,
                showCheckboxColumn: false,
                columns: const [
                  DataColumn(
                    label: CustomText(
                      text: "No.",
                      weight: FontWeight.bold,
                    ),
                  ),
                  DataColumn(
                    label: CustomText(
                      text: "Name",
                      weight: FontWeight.bold,
                    ),
                  ),
                  DataColumn(
                    label: CustomText(
                      text: "Address",
                      weight: FontWeight.bold,
                    ),
                  ),
                  DataColumn(
                    label: CustomText(
                      text: "Contact Person",
                      weight: FontWeight.bold,
                    ),
                  ),
                  DataColumn(
                    label: CustomText(
                      text: "Phone Number",
                      weight: FontWeight.bold,
                    ),
                  ),
                  DataColumn(
                    label: CustomText(
                      text: "Status",
                      weight: FontWeight.bold,
                    ),
                  ),
                  DataColumn(
                    label: CustomText(
                      text: "Tools",
                      weight: FontWeight.bold,
                    ),
                  ),
                ],
                rows: providerListItems(),
              ),
            );
          } else {
            return const Text('No data...');
          }
        case ConnectionState.done:
          return const Text('Something went wrong');
        default:
          return const Text('Something went wrong');
      }
    });

}

Is there something that I did wrong? Or is it a bug? Is the problem like I thought it is that data is not updated, so stream builder only builds once? If so, can you provide a solution for me, I can't seem to find the solution... Thank you!

--> EDIT

Initialization of providerDBsnaps

@override
void initState() {
  super.initState();
  providerDBsnaps = providerDB.snapshots();
  providerDBsnaps.listen((snapshot) {
  if (snapshot.docs.isNotEmpty) {
    final List<DocumentSnapshot> documents = snapshot.docs;

    providers = documents
        .map((e) => ProviderList.fromMap(e.data() as Map<String, dynamic>))
        .toList();
  }
});
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心碎的声音 2025-02-16 23:34:37

连接状态将保留在“等待”中,直到发送新快照为止。

解决它的一种方法是将您的流构建器放入状态fullwidget中,以便保持“提供者”的状态。

在您的州类中,函数“ ProviderListItems”可以在流构建器之外。

然后,您的FutureBuilder可能会像:

builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
  switch (snapshot.connectionState) {
    case ConnectionState.none:
    case ConnectionState.done:
      return const Text('Something went wrong');
    case ConnectionState.active:
      if (snapshot.hasData) {
        final List<DocumentSnapshot> documents = snapshot.data!.docs;
        providers = documents
            .map((e) =>
                ProviderList.fromMap(e.data() as Map<String, dynamic>))
            .toList();
      } else {
        providers = [];
      }
      break;
    default:
      break;
  }
  if(providers.isNotEmpty) {
    return Container(
      ...
      );
  } else {
    return const Text('No data...');
  }

我认为更容易的另一种方式是在发送事件时聆听您在Initstate内部的流并更新提供商。

class _MyWidget extends State<MyWidget> {
  List providers = [];

  @override
  void initState() {
    providerDBsnaps.listen((snapshot) {
      if (snapshot.hasData) {
        final List<DocumentSnapshot> documents = snapshot.data!.docs;
        providers = documents
                .map((e) =>
                    ProviderList.fromMap(e.data() as Map<String, dynamic>))
                .toList();
       } else {
            providers = [];
       }
       setState((){});
    };
  }
  
  @override
  Widget build(BuildContext context) {
      if(providers.isNotEmpty) {
        return Container(
          ...
          );
      } else {
        return const Text('No data...');
      }
  }

  List<DataRow> providerListItems() {
    final List<DataRow> providerList = [];
    ...
    return providerList;
  }

The connection state will remain in "Waiting" until a new snapshot is sent.

One way to solve it is to have your StreamBuilder inside a StatefullWidget so you can keep the state of "providers".

The function "providerListItems" could be outside the StreamBuilder, in your State class.

Then your FutureBuilder could be something like:

builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
  switch (snapshot.connectionState) {
    case ConnectionState.none:
    case ConnectionState.done:
      return const Text('Something went wrong');
    case ConnectionState.active:
      if (snapshot.hasData) {
        final List<DocumentSnapshot> documents = snapshot.data!.docs;
        providers = documents
            .map((e) =>
                ProviderList.fromMap(e.data() as Map<String, dynamic>))
            .toList();
      } else {
        providers = [];
      }
      break;
    default:
      break;
  }
  if(providers.isNotEmpty) {
    return Container(
      ...
      );
  } else {
    return const Text('No data...');
  }

Another way, in my opinion easier, would be to listen to your stream inside the InitState and update the providers when an event is sent.

class _MyWidget extends State<MyWidget> {
  List providers = [];

  @override
  void initState() {
    providerDBsnaps.listen((snapshot) {
      if (snapshot.hasData) {
        final List<DocumentSnapshot> documents = snapshot.data!.docs;
        providers = documents
                .map((e) =>
                    ProviderList.fromMap(e.data() as Map<String, dynamic>))
                .toList();
       } else {
            providers = [];
       }
       setState((){});
    };
  }
  
  @override
  Widget build(BuildContext context) {
      if(providers.isNotEmpty) {
        return Container(
          ...
          );
      } else {
        return const Text('No data...');
      }
  }

  List<DataRow> providerListItems() {
    final List<DataRow> providerList = [];
    ...
    return providerList;
  }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文