您好,登錄后才能下訂單哦!
如何在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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。