当应用程序在Flutter中打开时,如何显示快餐栏或底部工作表?

因此,我有一个要求,我需要在该位置显示Snackbar应用程序启动时的状态,但是当我尝试执行该操作时,它会显示上下文错误。我怎么知道我的窗口小部件树已构建并使用上下文显示Snackbar

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {

// This widget is the root of your application.

@override

Widget build(BuildContext context) {

return new MaterialApp(

title: 'Flutter Demo',

theme: new ThemeData(

primarySwatch: Colors.blue,

),

home: new MyHomePage(title: 'Flutter Demo Home Page'),

);

}

}

class MyHomePage extends StatefulWidget {

MyHomePage({Key key, this.title}) : super(key: key);

final String title;

@override

_MyHomePageState createState() => new _MyHomePageState();

}

class _MyHomePageState extends State<MyHomePage> {

@override

Widget build(BuildContext context) {

Scaffold.of(context).showSnackBar(SnackBar(content: Text('Welcome User')));

return new Scaffold(

appBar: new AppBar(

title: new Text(widget.title),

),

body: new Center(

child: new Column(

mainAxisAlignment: MainAxisAlignment.center,

children: <Widget>[],

),

),

);

}

}

回答:

创建类型为ScaffoldState的GlobalKey,以确保您以正确的Scaffold为目标,以在其上显示SnackBar。

将目标脚手架的密钥设置为您创建的密钥。

在initState()函数中,使用WidgetsBinding类和addPostFrameCallback在构建布局时执行代码。在回叫中显示您的SnackBar。

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {

// This widget is the root of your application.

@override

Widget build(BuildContext context) {

return new MaterialApp(

title: 'Flutter Demo',

theme: new ThemeData(

primarySwatch: Colors.blue,

),

home: new MyHomePage(title: 'Flutter Demo Home Page'),

);

}

}

class MyHomePage extends StatefulWidget {

MyHomePage({Key key, this.title}) : super(key: key);

final String title;

@override

_MyHomePageState createState() => new _MyHomePageState();

}

class _MyHomePageState extends State<MyHomePage> {

var _scaffoldKey = GlobalKey<ScaffoldState>();

@override

void initState() {

super.initState();

WidgetsBinding.instance.addPostFrameCallback((_) => _scaffoldKey.currentState.showSnackBar(SnackBar(content: Text('Welcome User'))));

}

@override

Widget build(BuildContext context) {

return new Scaffold(

key: _scaffoldKey,

appBar: new AppBar(

title: new Text(widget.title),

),

body: new Center(

child: new Column(

mainAxisAlignment: MainAxisAlignment.center,

children: <Widget>[],

),

),

);

}

}

以上是 当应用程序在Flutter中打开时,如何显示快餐栏或底部工作表? 的全部内容, 来源链接: utcz.com/qa/402516.html

回到顶部