本文介绍了页面转换后如何显示SnackBar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只想在页面显示时显示SnackBar.但是我们不能在构建方法中调用showSnackBar.
I want to show SnackBar only once when the page is displayed.But we can not call showSnackBar in build method.
构建后是否有调用处理程序?
Is there a handler that called after build?
推荐答案
您可以使用StatefulWidget
并在State
的initState
中调用showSnackBar
.您需要在触发showSnackBar
之前添加一个短暂的延迟.这是一个代码示例.
You could use a StatefulWidget
and call showSnackBar
in the initState
of your State
. You will need to add a short delay before triggering showSnackBar
. Here is a code sample.
import 'dart:async';
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new HomePage(),
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Scaffold(
floatingActionButton: new FloatingActionButton(
child: new Icon(Icons.developer_board),
onPressed: () {
Navigator.of(context).push(
new MaterialPageRoute(builder: (_) => new MySecondPage()),
);
},
),
);
}
}
class MySecondPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Developer Mode'),
),
body: new MySecondPageBody(),
);
}
}
class MySecondPageBody extends StatefulWidget {
@override
State createState() => new MySecondPageBodyState();
}
class MySecondPageBodyState extends State<MySecondPageBody> {
@override
void initState() {
new Future<Null>.delayed(Duration.ZERO, () {
Scaffold.of(context).showSnackBar(
new SnackBar(content: new Text("You made it! Congrats.")),
);
});
super.initState();
}
@override
Widget build(BuildContext context) {
return new Center(
child: new Text('You are now a developer.'),
);
}
}
这篇关于页面转换后如何显示SnackBar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!