所以我有一个要求,我需要在应用程序启动时显示const
,但是当我尝试这样做时,它会给我带来上下文错误。我怎么知道我的窗口小部件树已构建并使用上下文显示std::string(*)()
。
unsigned int(*)(const std::string&)
答案 0 :(得分:4)
创建类型为GlobalKey的ScaffoldState,以确保您定位正确的脚手架以在其上显示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>[],
),
),
);
}
}
答案 1 :(得分:0)
您不需要GlobalKey
,Builder
或类似的任何典型内容。只需使用ScaffoldMessenger.of(context).showSnackBar()
。
完整代码:
void main() => runApp(MaterialApp(home: HomePage()));
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
void initState() {
super.initState();
final snackBar = SnackBar(content: Text('Hi'));
Future(() => ScaffoldMessenger.of(context).showSnackBar(snackBar));
}
@override
Widget build(BuildContext context) => Scaffold();
}