zoukankan      html  css  js  c++  java
  • flutter SnackBar异常Another exception was thrown: Scaffold.of() called with a context that does not contain a Scaffold

    代码如下:

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(MaterialApp(
        title: 'Returning Data',
        home: HomePage(),
      ));
    }
    
    class HomePage extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Flutter SnackBar'),
          ),
          body: Center(
            child: MaterialButton(
              color: Colors.blue,
              child: new Text('点我'),
              onPressed: () {
                final snackBar = new SnackBar(content: new Text('这是一个SnackBar'));
                Scaffold.of(context).showSnackBar(snackBar);
              },
            ),
          ),
        );
      }
    }

    当BuildContext在Scaffold之前时,调用Scaffold.of(context)会报错。这时可以通过Builder Widget来解决,代码如下:

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(MaterialApp(
        title: 'Returning Data',
        home: HomePage(),
      ));
    }
    
    class HomePage extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Flutter SnackBar'),
          ),
          body: Builder(
            builder: (BuildContext context) {
              return new Center(
                  child: MaterialButton(
                      color: Colors.blue,
                      child: new Text('点我'),
                      onPressed: () {
                        final snackBar =
                            new SnackBar(content: new Text('这是一个SnackBar'));
                        Scaffold.of(context).showSnackBar(snackBar);
                      }));
            },
          ),
        );
      }
    }
  • 相关阅读:
    Yarn架构基本概况(二)
    Yarn架构基本概况(二)
    Yarn架构基本概况(二)
    Yarn架构基本概况(一)
    Yarn架构基本概况(一)
    Yarn架构基本概况(一)
    从Hadoop 安全机制原理到当今主流安全机制
    WebService数据示例
    CXF浅析
    WebService的网络协议
  • 原文地址:https://www.cnblogs.com/mingfeng002/p/11592228.html
Copyright © 2011-2022 走看看