簡體   English   中英

Flutter,錯誤,在應用程序中添加數據時,firebase

[英]Flutter, error, when add data in app , firebase

我有一個問題,所有代碼都能正常工作,在應用程序和 firebase 控制台中,一切都很容易加起來,沒有崩潰,但是當單擊添加數據的按鈕時,我出現錯誤:“發生異常。StateError(錯誤 state:調用關閉后無法發出新狀態)” . 我沒有在任何地方找到解決方案

我的 state:

part of 'add_page_cubit.dart';

class AddPageState {
  const AddPageState({
    this.saved = false,
    this.errorMessage = '',
  });

  final bool saved;
  final String errorMessage;
}

我的腕尺:

import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
part 'add_page_state.dart';

class AddPageCubit extends Cubit<AddPageState> {
  AddPageCubit() : super(const AddPageState());

  StreamSubscription? _streamSubscription;
  Future<void> add(
    String product,
    String shopName,
    String category,
  ) async {
    try {
      _streamSubscription =
          (await FirebaseFirestore.instance.collection('shoppingList').add(
        {
          'product': product,
          'shopName': shopName,
          'category': category,
        },
      )) as StreamSubscription?;
      emit(
        const AddPageState(
          saved: true,
        ),
      );
    } catch (error) {
      emit(
        AddPageState(
          errorMessage: error.toString(),
        ),
      );
    }
  }

  @override
  Future<void> close() {
    _streamSubscription?.cancel();
    return super.close();
  }
}

**頁面內容:**

class AddPage extends StatefulWidget {
  const AddPage({
    required this.onSave,
    Key? key,
  }) : super(key: key);

  final Function onSave;

  @override
  State<AddPage> createState() => _AddPageState();
}

class _AddPageState extends State<AddPage> {
  String? _product;
  String? _shopName;
  String? _category;

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => AddPageCubit(),
      child: BlocBuilder<AddPageCubit, AddPageState>(
        builder: (context, state) {
          if (state.errorMessage.isNotEmpty) {
            return Center(
              child: Text('Someting went wrong ${state.errorMessage}!'),
            );
          }

          return Center(
            child: Padding(
              padding: const EdgeInsets.all(25.0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  TextField(
                    decoration: const InputDecoration(
                      hintText: 'Podaj nazwę produktu',
                    ),
                    onChanged: (newValue) {
                      setState(
                        () {
                          _product = newValue;
                        },
                      );
                    },
                  ),
                  const SizedBox(
                    height: 30,
                  ),
                  TextField(
                    decoration: const InputDecoration(
                      hintText: 'Podaj nazwę/rodzaj sklepu',
                    ),
                    onChanged: (newValue) {
                      setState(
                        () {
                          _shopName = newValue;
                        },
                      );
                    },
                  ),
                  const SizedBox(
                    height: 30,
                  ),
                  DropdownButton<String>(
                    focusColor: Colors.white,
                    value: _category,
                    style: const TextStyle(color: Colors.white),
                    iconEnabledColor: Colors.black,
                    items: listOfCategory
                        .map<DropdownMenuItem<String>>((String value) {
                      return DropdownMenuItem<String>(
                        value: value,
                        child: Padding(
                          padding: const EdgeInsets.only(
                            left: 42,
                          ),
                          child: Text(
                            value,
                            style: const TextStyle(
                              color: Colors.black,
                              fontSize: 18,
                            ),
                          ),
                        ),
                      );
                    }).toList(),
                    hint: const Text(
                      "Choose an category",
                      style: TextStyle(
                        fontSize: 20,
                      ),
                    ),
                    onChanged: (String? newValue) {
                      setState(() {
                        _category = newValue!;
                      });
                    },
                  ),
                  const SizedBox(
                    height: 36,
                  ),
                  ElevatedButton(
                    onPressed: _product == null || _shopName == null
                        ? null
                        : () {
                            context.read<AddPageCubit>().add(
                                  _product!,
                                  _shopName!,
                                  _category!,
                                );
                            widget.onSave();
                          },
                    child: const Text('Dodaj'),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}

並在我出錯時打開 block_base.dart 代碼(也許可以幫助某人)

@protected
  @visibleForTesting
  @override
  void emit(State state) {
    try {
      if (isClosed) {
        throw StateError('Cannot emit new states after calling close');
      }
      if (state == _state && _emitted) return;
      onChange(Change<State>(currentState: this.state, nextState: state));
      _state = state;
      _stateController.add(_state);
      _emitted = true;
    } catch (error, stackTrace) {
      onError(error, stackTrace);
    ***  rethrow;***
    }
  }

.yaml

  firebase_core: ^2.3.0
  firebase_auth: ^4.1.3
  flutterfire_ui: ^0.4.3+20
  cloud_firestore: ^4.1.0
  flutter_bloc: ^8.1.1

當我單擊繼續時,所有數據都會正常添加。感謝您的每一個提示。

我刪除了我添加的所有數據,檢查了拼寫,在 firebase 控制台數據庫中重新創建

只有一個答案:有些東西離你的bloc很近,你不能在那里發出新的價值 您的bloc可能有 memory 泄漏,並且此錯誤發生在屏幕上不再顯示的前一個bloc上。

嘗試在異常前放置一個斷點並檢查堆棧跟蹤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM