flutter SnackBar异常Another exception was thrown: Scaffold.of() called with a context that does not co

代码如下:

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);
                  }));
        },
      ),
    );
  }
}

 

上一篇:基于Keil uVision5和Proteus 8 Professional,led循环点亮


下一篇:flutter_swiper:Another exception was thrown: ScrollController attached to multiple scroll views.