Display SnackBar in Flutter

前端 未结 15 1488
一个人的身影
一个人的身影 2020-12-04 19:28

I want to display a simple SnackBar inside Flutter\'s stateful widget. My application creates new instance of MaterialApp with a stateful widget ca

15条回答
  •  再見小時候
    2020-12-04 19:54

    The best way is to create a PageWrapper that you can wrap all of your pages to get the context of the Scaffold widget and avoid experiencing these errors again.

    Here is a sample of the page wrapper:

    import 'package:flutter/material.dart';
    
    class PageWrapper extends StatelessWidget {
    
      Widget page;
    
      WPage(this.page);
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          backgroundColor: Colors.white,
          body: page
        );
      }
    }
    

    Then you can wrap all your pages in the main.dart like these:

    import 'package:flutter/material.dart';
    void main() => runApp(MaterialApp(
      initialRoute: '/login',
      routes: {
        '/login': (context) => PageWrapper(Login()),
        '/home': (context) => PageWrapper(Home())
      }
    ));
    

    Now you can call Scaffold.of(context) anywhere in any page just fine.

    Reference: https://noobieprogrammer.blogspot.com/2020/06/how-to-create-error-alert-or-popup.html

    or watch the video version (5 min. long): https://youtu.be/u9KoFtu0HEY

提交回复
热议问题