简体   繁体   中英

Flutter : this error appear Scaffold.of() called with a context that does not contain a Scaffold. when i try to show a snackbar

  • I try to use a snackBar when the connectivity status changed, and the connectivity works fine when I use a print. But when I try to use a Scaffold.of(context).showSnackBar....,

  • i got an error with ['Scaffold.of() called with a context that does not contain a Scaffold.

No Scaffold ancestor could be found starting from the context that was passed to Scaffold.of(). This usually happens when the context provided is from the same StatefulWidget as that whose build function actually creates the Scaffold widget being sought.

']

  • I create a wrapper class which include a Widget as a constructor


import 'package:Zabatnee/activities_app/enum/connectivity_status.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';


class ConnectivityWrapper extends StatefulWidget {
  final Widget childWidget;
  ConnectivityWrapper(this.childWidget);

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

class _ConnectivityWrapperState extends State<ConnectivityWrapper> {

 Widget _showOfflineSnakbar(){
Scaffold.of(context).showSnackBar(
                SnackBar(
                  content: 
                  
                  Text(
                    'No internet connection',
                  ),
                  duration: Duration(seconds: 3),
                ),
              );

            
           
  }

  @override
  void didChangeDependencies() {
 var connectionState = Provider.of<ConnectivityStatus>(context);

    if(connectionState == ConnectivityStatus.Offline){
          print('the internet is offline');
           _showOfflineSnakbar();

     
    }if(connectionState == ConnectivityStatus.Wifi || connectionState == ConnectivityStatus.Cellular){
    print('the internet is online');
           _showOfflineSnakbar();

    }
    super.didChangeDependencies();
  }
  @override
  Widget build(BuildContext context) {
    return widget.childWidget;
  }
}
  • and in main.dart I use the wrapper class as a HomePage and put inside it the real homeScreen:
 home: ConnectivityWrapper(
             CategoriesScreen(),
            
            ),

Well, it seems like you haven't constructed a Scaffold in any parent widgets.

Either do that, or have a look at the Flushbar package.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM