当显示消息栏时,调用了不包含脚手架的上下文的 Scaffold.of() 错误。

10 浏览
0 Comments

当显示消息栏时,调用了不包含脚手架的上下文的 Scaffold.of() 错误。

这个问题已经有了答案:

Scaffold.of() called with a context that does not contain a Scaffold

在我的屏幕上,我有一个ScrollablePositionedList.builder,我正在使用slidable来滑动删除数据库中的记录,在弹出显示确认对话框并且用户确认删除后,我想显示一个撤消的菜单。在添加确认对话框之前,Snackbar就已经被很好的展示了,但是现在我得到了Scaffold.of() called with a context that does not contain a Scaffold的错误。我需要在显示它之前调用Navigator.pop(context)来关闭确认对话框,因此我认为这是原因,我尝试将其注释掉,但仍然会出现错误信息。

你能发现我做错了什么吗?同时我想在BlocListerBookingDeleted状态中接收到时显示Snackbar,但它在Scaffold之前,如何实现?

感谢您的帮助。

这是屏幕代码:

class _BookingsScreenState extends State {
  dynamic backButton = Platform.isIOS ? CupertinoIcons.back : Icons.arrow_back;
  DateFormat dateOnlyFormat =
      DateFormat.yMMMMEEEEd(AppLocalizations.instance.text('Language code'));
  DateFormat timeFormat = DateFormat('Hm');
  AudioCache cache = new AudioCache();
  ItemScrollController scrollController = ItemScrollController();
  List bookings = [];
  int cellIndex = 0;
  @override
  Widget build(BuildContext context) {
    cache.loadAll(['click.mp3', 'tableViewOpen.mp3', 'tableViewClose.mp3']);
    return BlocListener<BookingBloc, BookingState>(
      listener: (BuildContext context, BookingState state) {
        if (state is LoadedBookings) {
          setState(() {
            bookings = state.bookings;
            print(
                'BookingsScreen BlocListener we have  ${state.bookings.length} saved bookings');
            print(
                'BookingsScreen BlocListener saved bookings are ${state.bookings}');
            print(bookings);
          });
        }
        if (state is BookingDeleted) {
          showDialog(
            barrierDismissible: false,
            context: context,
            builder: (BuildContext context) {
              return BookingDeletedConfirmationDialog();
            }
          );
          Timer(Duration(milliseconds: 1500), (){
            cache.play('tableViewClose.mp3');
            Navigator.of(context, rootNavigator: false).pop(context);
          });
        }
      },
      child: Stack(
        children: [
          Image(
              image: widget.bgImage.image,
              height: MediaQuery.of(context).size.height,
              width: MediaQuery.of(context).size.width,
              fit: BoxFit.cover),
          Scaffold(
            backgroundColor: Colors.transparent,
            appBar: AppBar(
              elevation: 0,
              centerTitle: true,
              leading: IconButton(
                  icon: Icon(backButton),
                  color: Colors.redAccent,
                  onPressed: () {
                    cache.play('tableViewClose.mp3');
                    Navigator.pop(context);
                  }),
              title: Text(
                AppLocalizations.instance.text('BookingScreenTitle'),
                style: TextStyle(
                    color: Colors.orange,
                    fontSize: 22,
                    fontWeight: FontWeight.w500,
                    letterSpacing: 1),
              ),
              backgroundColor: Colors.transparent,
            ),
            body: SafeArea(
              minimum: EdgeInsets.symmetric(horizontal: 20),
              child: ScrollablePositionedList.builder(
                itemScrollController: scrollController,
                itemCount: bookings.length,
                itemBuilder: (BuildContext context, int index) => Slidable(
                  actionPane: SlidableBehindActionPane(),
                  actionExtentRatio: 0.25,
                  actions: [
                    IconSlideAction(
                      caption:
                          AppLocalizations.instance.text('Booking details'),
                      color: Colors.transparent,
                      foregroundColor: Colors.blue,
                      icon: Icons.details,
                      onTap: () {
                        print('BookingDetailsScreen');
                      },
                    ),
                  ],
                  secondaryActions: [
                    IconSlideAction(
                      caption: AppLocalizations.instance.text('Delete booking'),
                      color: Colors.transparent,
                      foregroundColor: Colors.red,
                      icon: Icons.delete,
                      onTap: () {
                        setState(() {
                          cellIndex = index;
                        });
                        var booking = bookings.elementAt(index);
                        if (booking.bookingState == 'Waiting' || booking.bookingState == 'Received' || booking.bookingState == 'Cancelled') {
                          showDialog(
                            context: context,
                            barrierDismissible: false,
                            builder: (BuildContext context) {
                              return BookingDeletionConfirmationDialog(
                                index: index,
                                booking: booking,
                                onPressedCancel: (){
                                  cache.play('tableViewClose.mp3');
                                  Navigator.pop(context);
                                  },
                                onPressedDelete: (){
                                  cache.play('tableViewClose.mp3');
                                  Navigator.pop(context);
                                  deleteItem(index, booking);
                                  //Scaffold.of() called with a context that does not contain a Scaffold. ???
                                  Scaffold.of(context).showSnackBar(SnackBar(
                                      backgroundColor: Colors.redAccent,
                                      content: Text(
                                        AppLocalizations.instance
                                            .text('Booking deleted'),
                                        style: TextStyle(color: Colors.white),
                                      ),
                                      action: SnackBarAction(
                                          textColor: Colors.white,
                                          label: AppLocalizations.instance.text('Undo'),
                                          onPressed: () {
                                            //To undo deletion
                                            undoDeletion(index, booking);
                                          })));
                                  },
                              );
                            }
                          );
                        } else {
                          Scaffold.of(context).showSnackBar(SnackBar(
                            backgroundColor: Colors.redAccent,
                            content: Text(
                              AppLocalizations.instance
                                  .text('Booking not deletable'),
                              style: TextStyle(color: Colors.white),
                            ),
                          ));
                        }
                      },
                    ),
                  ],
                  child: BookingCell(
                    isSelected: false,
                    borderColor: bookings[index].bookingState == 'Waiting'
                        ? Colors.blue
                        : bookings[index].bookingState == 'Received'
                            ? Colors.amber.shade200
                            : bookings[index].bookingState == 'Started'
                                ? Colors.amber.shade600
                                : bookings[index].bookingState == 'Completed'
                                    ? Colors.green.shade400
                                    : bookings[index].bookingState ==
                                            'Cancelled'
                                        ? Colors.redAccent
                                        : Colors.blueGrey.shade300,
                    worksList: bookings[index].worksNameList,
                    bookingId: bookings[index].bookingId.toString(),
                    bookingDate: dateOnlyFormat.format(
                        DateTime.fromMillisecondsSinceEpoch(
                            bookings[index].bookingDate)),
                    bookingStart: timeFormat.format(
                        DateTime.fromMillisecondsSinceEpoch(
                            bookings[index].bookingStart)),
                    shopName: bookings[index].shopName,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
  void deleteItem(index, Booking booking) {
    setState(() {
      BlocProvider.of(context).add(DeleteBooking(
          booking: booking,
          cityDb: widget.cityDb,
          regionDb: widget.regionDb,
          countryDb: widget.countryDb));
    });
    BlocProvider.of(context).add(UpdateBookingState(
        bookingId: booking.bookingId.toString(), state: 'Cancelled'));
  }
  void undoDeletion(index, Booking booking) {
    setState(() {
    booking.bookingState ='Reactivated.'+ booking.bookingState;
      BlocProvider.of(context).add(SaveBooking(
          booking: booking,
          cityDb: widget.cityDb,
          regionDb: widget.regionDb,
          countryDb: widget.countryDb));
    });
  }
}

admin 更改状态以发布 2023年5月21日
0
0 Comments

尝试使用脚手架全局密钥解决此问题。\n

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class _BookingsScreenState extends State {
  dynamic backButton = Platform.isIOS ? CupertinoIcons.back : Icons.arrow_back;
  DateFormat dateOnlyFormat =
      DateFormat.yMMMMEEEEd(AppLocalizations.instance.text('Language code'));
  DateFormat timeFormat = DateFormat('Hm');
  AudioCache cache = new AudioCache();
  ItemScrollController scrollController = ItemScrollController();
  List bookings = [];
  int cellIndex = 0;
  // scaffold global key
  GlobalKey scaffoldKey = GlobalKey();
  @override
  Widget build(BuildContext context) {
    cache.loadAll(['click.mp3', 'tableViewOpen.mp3', 'tableViewClose.mp3']);
    return BlocListener(
      listener: (BuildContext context, BookingState state) {
        if (state is LoadedBookings) {
          setState(() {
            bookings = state.bookings;
            print(
                'BookingsScreen BlocListener we have  ${state.bookings.length} saved bookings');
            print(
                'BookingsScreen BlocListener saved bookings are ${state.bookings}');
            print(bookings);
          });
        }
        if (state is BookingDeleted) {
          showDialog(
              barrierDismissible: false,
              context: context,
              builder: (BuildContext context) {
                return BookingDeletedConfirmationDialog();
              });
          Timer(Duration(milliseconds: 1500), () {
            cache.play('tableViewClose.mp3');
            Navigator.of(context, rootNavigator: false).pop(context);
          });
        }
      },
      child: Stack(
        children: [
          Image(
              image: widget.bgImage.image,
              height: MediaQuery.of(context).size.height,
              width: MediaQuery.of(context).size.width,
              fit: BoxFit.cover),
          Scaffold(
            // assign the key
            key: scaffoldKey,
            backgroundColor: Colors.transparent,
            appBar: AppBar(
              elevation: 0,
              centerTitle: true,
              leading: IconButton(
                  icon: Icon(backButton),
                  color: Colors.redAccent,
                  onPressed: () {
                    cache.play('tableViewClose.mp3');
                    Navigator.pop(context);
                  }),
              title: Text(
                AppLocalizations.instance.text('BookingScreenTitle'),
                style: TextStyle(
                    color: Colors.orange,
                    fontSize: 22,
                    fontWeight: FontWeight.w500,
                    letterSpacing: 1),
              ),
              backgroundColor: Colors.transparent,
            ),
            body: SafeArea(
              minimum: EdgeInsets.symmetric(horizontal: 20),
              child: ScrollablePositionedList.builder(
                itemScrollController: scrollController,
                itemCount: bookings.length,
                itemBuilder: (BuildContext context, int index) => Slidable(
                  actionPane: SlidableBehindActionPane(),
                  actionExtentRatio: 0.25,
                  actions: [
                    IconSlideAction(
                      caption:
                          AppLocalizations.instance.text('Booking details'),
                      color: Colors.transparent,
                      foregroundColor: Colors.blue,
                      icon: Icons.details,
                      onTap: () {
                        print('BookingDetailsScreen');
                      },
                    ),
                  ],
                  secondaryActions: [
                    IconSlideAction(
                      caption: AppLocalizations.instance.text('Delete booking'),
                      color: Colors.transparent,
                      foregroundColor: Colors.red,
                      icon: Icons.delete,
                      onTap: () {
                        setState(() {
                          cellIndex = index;
                        });
                        var booking = bookings.elementAt(index);
                        if (booking.bookingState == 'Waiting' ||
                            booking.bookingState == 'Received' ||
                            booking.bookingState == 'Cancelled') {
                          showDialog(
                              context: context,
                              barrierDismissible: false,
                              builder: (BuildContext context) {
                                return BookingDeletionConfirmationDialog(
                                  index: index,
                                  booking: booking,
                                  onPressedCancel: () {
                                    cache.play('tableViewClose.mp3');
                                    Navigator.pop(context);
                                  },
                                  onPressedDelete: () {
                                    cache.play('tableViewClose.mp3');
                                    Navigator.pop(context);
                                    deleteItem(index, booking);
                                    //Scaffold.of() called with a context that does not contain a Scaffold. ???
                                    scaffoldKey.currentState.showSnackBar(
                                        SnackBar(
                                            backgroundColor: Colors.redAccent,
                                            content: Text(
                                              AppLocalizations.instance
                                                  .text('Booking deleted'),
                                              style: TextStyle(
                                                  color: Colors.white),
                                            ),
                                            action: SnackBarAction(
                                                textColor: Colors.white,
                                                label: AppLocalizations.instance
                                                    .text('Undo'),
                                                onPressed: () {
                                                  //To undo deletion
                                                  undoDeletion(index, booking);
                                                })));
                                  },
                                );
                              });
                        } else {
                          scaffoldKey.currentState.showSnackBar(SnackBar(
                            backgroundColor: Colors.redAccent,
                            content: Text(
                              AppLocalizations.instance
                                  .text('Booking not deletable'),
                              style: TextStyle(color: Colors.white),
                            ),
                          ));
                        }
                      },
                    ),
                  ],
                  child: BookingCell(
                    isSelected: false,
                    borderColor: bookings[index].bookingState == 'Waiting'
                        ? Colors.blue
                        : bookings[index].bookingState == 'Received'
                            ? Colors.amber.shade200
                            : bookings[index].bookingState == 'Started'
                                ? Colors.amber.shade600
                                : bookings[index].bookingState == 'Completed'
                                    ? Colors.green.shade400
                                    : bookings[index].bookingState ==
                                            'Cancelled'
                                        ? Colors.redAccent
                                        : Colors.blueGrey.shade300,
                    worksList: bookings[index].worksNameList,
                    bookingId: bookings[index].bookingId.toString(),
                    bookingDate: dateOnlyFormat.format(
                        DateTime.fromMillisecondsSinceEpoch(
                            bookings[index].bookingDate)),
                    bookingStart: timeFormat.format(
                        DateTime.fromMillisecondsSinceEpoch(
                            bookings[index].bookingStart)),
                    shopName: bookings[index].shopName,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
  void deleteItem(index, Booking booking) {
    setState(() {
      BlocProvider.of(context).add(DeleteBooking(
          booking: booking,
          cityDb: widget.cityDb,
          regionDb: widget.regionDb,
          countryDb: widget.countryDb));
    });
    BlocProvider.of(context).add(UpdateBookingState(
        bookingId: booking.bookingId.toString(), state: 'Cancelled'));
  }
  void undoDeletion(index, Booking booking) {
    setState(() {
      booking.bookingState = 'Reactivated.' + booking.bookingState;
      BlocProvider.of(context).add(SaveBooking(
          booking: booking,
          cityDb: widget.cityDb,
          regionDb: widget.regionDb,
          countryDb: widget.countryDb));
    });
  }
}

0