gpt4 book ai didi

dart - flutter 中的启动画面实现

转载 作者:IT王子 更新时间:2023-10-29 07:08:30 25 4
gpt4 key购买 nike

我是 Flutter 的新手,我想在我的应用程序中使用启动画面。我使用了 initState() 和导航器。但它没有用。该应用程序打开出现启动画面,但之后它不会导航到下一个屏幕。

我的 main.dart

import 'package:flutter/material.dart';
import 'package:bmi/HomePage.dart';
import 'dart:async';

main(){
runApp(MyApp());
}

class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context) {
return SplashScreen();
}
}

class SplashScreen extends StatefulWidget{
@override
State<StatefulWidget> createState() {
return SplashScreenState();
}
}

class SplashScreenState extends State<SplashScreen>{
@override
void initState() {
super.initState();
Future.delayed(
Duration(
seconds: 4
),
(){
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => HomePage(),
)
);
}
);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.red,
body: Text(
'Welcome to BMI Calculator',
style: new TextStyle(
fontSize: 15.0,
color: Colors.white,
fontWeight: FontWeight.bold
),
),
),
);
}
}

还有我的 HomePage.dart

import 'package:flutter/material.dart';

class HomePage extends StatelessWidget{
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
backgroundColor: Colors.red,
title: Text(
'BMI Calculator',
style: new TextStyle(
color: Colors.white
),
),
),
),
);
}
}

我该如何解决?

由于我是 flutter 的新手,所以我不知道这是否是实现 splashScreen 的正确方法,如果有任何其他更简单的方法,您能否也提出建议。

提前谢谢你。

最佳答案

代码更正:

MaterialApp should be the parent(root) of all Widgets.

import 'package:flutter/material.dart';
import 'package:bmi/HomePage.dart';
import 'dart:async';

main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(home: SplashScreen()); // define it once at root level.
}
}

class SplashScreen extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return SplashScreenState();
}
}

class SplashScreenState extends State<SplashScreen> {
@override
void initState() {
super.initState();
Future.delayed(Duration(seconds: 4), () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => HomePage(),
));
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.red,
body: Text(
'Welcome to BMI Calculator',
style: new TextStyle(
fontSize: 15.0, color: Colors.white, fontWeight: FontWeight.bold),
),
);
}
}

class HomePage extends StatelessWidget{
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.red,
title: Text(
'BMI Calculator',
style: new TextStyle(
color: Colors.white
),
),
),
);
}

}

关于dart - flutter 中的启动画面实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54575622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com