如何在Flutter中确显示SnackBar?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
显示SnackBar,官方典型示例代码如下所示:
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Code Sample for Scaffold.of.', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( body: MyScaffoldBody(), appBar: AppBar(title: Text('Scaffold.of Example')), ), color: Colors.white, ); } } // 在Scaffold子组件里的build方法可以调用Scaffold.of方法 class MyScaffoldBody extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: RaisedButton( child: Text('SHOW A SNACKBAR'), onPressed: () { Scaffold.of(context).showSnackBar( SnackBar( content: Text('Have a snack!'), ), ); }, ), ); } }
但是若直接在构建Scallfold的build方法中调用会报异常:
Scaffold.of() called with a context that does not contain a Scaffold.
错误代码如下所示:
import 'package:flutter/material.dart'; class ScaffoldSnackBarDemo extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return Scaffold( body: Center( child: RaisedButton( child: Text('SHOW A SNACKBAR'), onPressed: () { ///直接在Scallfold的build方法里使用会抛异常 Scaffold.of(context).showSnackBar( SnackBar( content: Text('Have a snack!'), ), ); }, ), ), appBar: AppBar(title: Text('Scaffold.of Example')), ); } }
这时候要不就是按官方的,将需要显示SnackBar的代码另外抽离一个自定义子组件,在子组件的build方法再显示SnackBar,要不就是在Scaffold的build方法体对该子组件再包一层Builder,如下所示。
import 'package:flutter/material.dart'; class ScaffoldSnackBarDemo extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return Scaffold( ///在子组件外再包一层builder,让context不共用 body: Builder(builder: (context) { return Center( child: RaisedButton( child: Text('SHOW A SNACKBAR'), onPressed: () { Scaffold.of(context).showSnackBar( SnackBar( content: Text('Have a snack!'), ), ); }, ), ); }), appBar: AppBar(title: Text('Scaffold.of Example')), ); } }
import 'package:flutter/material.dart'; class ScaffoldSnackBarDemo extends StatelessWidget { final _scallfoldKey = GlobalKey<ScaffoldState>(); @override Widget build(BuildContext context) { return Scaffold( ///使用GlobalKey解决 key: _scallfoldKey, body: Center( child: RaisedButton( child: Text('SHOW A SNACKBAR'), onPressed: () { _scallfoldKey.currentState.showSnackBar(SnackBar( content: Text('Have a snack!'), )); }, ), ), appBar: AppBar(title: Text('Scaffold.of Example')), ); } }
看完上述内容,你们掌握如何在Flutter中确显示SnackBar的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。