小编典典

页面转换后如何显示SnackBar

flutter

当页面显示时,我只想显示一次SnackBar。但是我们不能在build方法中调用showSnackBar。

构建后是否有调用的处理程序?


阅读 372

收藏
2020-08-13

共1个答案

小编典典

你可以使用StatefulWidget和调用showSnackBarinitState你的State。您需要在触发之前添加一小段延迟showSnackBar。这是一个代码示例。

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.'),
    );
  }
}
2020-08-13