1

我有一个带有 2 个小部件/页面的颤振应用程序,即:
- 加载小部件/页面(在应用程序启动时出现
- 主页小部件/页面

我想在加载页面完成加载后启动主页。基本上我的问题是 -我怎样才能知道我的小部件何时完成加载?

以下是我的代码:

// My main.dart
import 'package:flutter/material.dart';
import 'package:routes/pages/home.dart';
import 'package:routes/pages/loading.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 Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      routes: {
        '/': (context) => Loading(),
        '/home': (context) => Home(),
      },
    );
  }
}

class Loading extends StatefulWidget {
  @override
  _LoadingState createState() => _LoadingState();
}

class _LoadingState extends State<Loading> {
  @override
  void initState() {
    super.initState();
    // Below line of code causes problem. How can I call to route to new page after current widget has completed loading 
    launchAnotherWidgetAfterDoingSomething();
  }

  void launchAnotherWidgetAfterDoingSomething() {
    // Do some necessary logic....
    Navigator.pushReplacementNamed(context, '/home');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Loading screen'),
      ),
    );
  }
}
4

1 回答 1

3

你可以试试这个

@override
void initState() {
  super.initState();

  // ...
  _gotoHome();
}

// ...

void _gotoHome() {
  Future.delayed(Duration.zero, () {
    Navigator.of(context).pushReplacementNamed('/home')
  });
}

编辑
要在页面中构建每个小部件后触发操作,请将其添加到您的initState

WidgetsBinding.instance.addPostFrameCallback((_) {
  // do what you want here
});
于 2020-12-28T20:32:36.290 回答