0

I want to add a Snack bar that tells a user to scroll up when images added to the body is more than 2..the problem is I can't put the snack bar in a scaffold because the add image button is just a reference in the scaffold widget. I'm new to asking questions so I might not have asked correctly.

class App extends StatefulWidget {
  createState() {
    return AppState();
  }
}

class AppState extends State<App> {
  int counter = 0;
  List<ImageModel> images = [];

  void fetchImage() async {
    counter++;
    while (counter > 2) {
      Scaffold.of(context).showSnackBar(SnackBar(
        content: Text('Scroll Up'),
        duration: Duration(seconds: 2),
      ));
    }
    var response =
        await get('http://jsonplaceholder.typicode.com/photos/$counter');

    var imageModel = ImageModel.fromJson(json.decode(response.body));
    setState(
      () {
        images.add(imageModel);
      },
    );
  }

  Widget build(context) {
    return MaterialApp(
      home: Scaffold(
        body: ImageList(images),
        backgroundColor: Colors.blueGrey.shade200,
        bottomNavigationBar: BottomAppBar(
          shape: const CircularNotchedRectangle(),
          child: Container(
            height: 50.0,
            //color: Colors.blue,
          ),
        ),
        floatingActionButton: FloatingActionButton(
          backgroundColor: Colors.blueGrey,
          child: Icon(Icons.add),
          onPressed: fetchImage,
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        appBar: AppBar(
          title: Text("Let's see images!"),
        ),
      ),
    );
  }
}
Akif
  • 7,098
  • 7
  • 27
  • 53

2 Answers2

0

You can try to send the context parameter while calling your fetchImage() method like this:

   onPressed: () 
         {
           fetchImage(context);
         }

And then:

   void fetchImage(BuildContext context) async {
   
Akif
  • 7,098
  • 7
  • 27
  • 53
0

The best and easiest way to show Snackbar is using GlobalKey. Just create an GlobalKey ,assign it to an Scaffold and use this key to show SnackBar. For example:

class _WidgetState extends State<YourStatefulWidget> {
  final scaffoldKey=GlobalKey<ScaffoldState>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key:scaffoldKey,
      body: Center(
        child: RaisedButton(
        child:Text("Press Me"),
        onPressed:(){
            scaffoldKey.currentState.showSnackBar(
            SnackBar(content:Text("YO"))
            );
          },
        ),
      ),
    );
  }
}
Faiizii Awan
  • 1,615
  • 1
  • 13
  • 28
Vinay Jain
  • 398
  • 2
  • 6
  • i was able to find my way to show the snackBar using the Global key but i figured that i couldnt condition the snackbar using a while loop.my device gets disconnected. – Akanmu Ademola Dec 17 '20 at 11:22