代码如下:

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

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-08-26
  • 2021-10-16
  • 2021-09-04
  • 2022-01-01
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-09-09
  • 2022-01-13
  • 2022-12-23
  • 2022-12-23
  • 2021-07-05
相关资源
相似解决方案