简体   繁体   English

在 main.dart 中将 Future 与 MaterialApp.router 结合使用

[英]Use Future with MaterialApp.router in main.dart

SITUATION: I'm trying to set up firebase with my flutter project by following this guide by the firebase team.情况:我正在尝试按照 firebase 团队的本指南,使用我的 flutter 项目设置 firebase。

PROBLEM: In the final steps of the guide, a FutureBuilder widget is passed to the 'home' property of a MaterialApp widget.问题:在本指南的最后步骤中,FutureBuilder 小部件被传递到 MaterialApp 小部件的“home”属性。 However, MaterialApp.router does not have a 'home' property, so I am struggling to complete the set-up (am new to flutter:-)).但是,MaterialApp.router 没有“home”属性,因此我正在努力完成设置(我是 flutter 的新手:-))。

Any thoughts on how to solve this problem?关于如何解决这个问题的任何想法?

// Import libraries
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:firebase_core/firebase_core.dart';

// Import custom widgets
import 'views/landing_page.dart';
import 'views/info_page.dart';


// Initiate the app
Future<void> main() async {
  // Ensure all services are loaded before app is started
  WidgetsFlutterBinding.ensureInitialized();
  // Run the app
  runApp(MyApp());
}


// Define the MyApp widget
class MyApp extends StatelessWidget {
  MyApp({Key? key}) : super(key: key);

  final Future<FirebaseApp> _fbApp = Firebase.initializeApp();

  // Build the website
  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routeInformationParser: _router.routeInformationParser,
      routerDelegate: _router.routerDelegate,
      debugShowCheckedModeBanner: false,
    );
  }

  // Declare routing information
  final _router = GoRouter(
    routes: [
      GoRoute(
        path: '/',
        builder: (context, state) => const LandingPage(),
      ),
      GoRoute(
        path: '/info',
        builder: (context, state) => const InfoPage(),
      ),
    ],
  );
}

figured this one out on my own.这个是我自己想出来的。 I did indeed need to just wrap the entire MaterialApp in a Futurebuilder我确实需要将整个 MaterialApp 包装在 Futurebuilder 中

 // Import libraries import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:firebase_core/firebase_core.dart'; // Import custom widgets import 'views/landing_page.dart'; import 'views/info_page.dart'; // Initiate the app Future<void> main() async { // Ensure all services are loaded before app is started WidgetsFlutterBinding.ensureInitialized(); // Run the app runApp(MyApp()); } // Define the MyApp widget class MyApp extends StatelessWidget { MyApp({Key? key}): super(key: key); final Future<FirebaseApp> _initializedApp = Firebase.initializeApp(); // Build the website @override Widget build(BuildContext context) { return return FutureBuilder( future: _initializedApp, builder: (context, snapshot) { if (snapshot.hasError) { return const Text('Something went wrong. Please try reloading;'). } else if (snapshot.hasData) { return MaterialApp:router( routeInformationParser. _router,routeInformationParser: routerDelegate. _router,routerDelegate: debugShowCheckedModeBanner, false; ): } else { return const Center( child: SizedBox( height, 150: width, 150: child, CircularProgressIndicator(), ); ), } }; ): // Declare routing information final _router = GoRouter( routes: [ GoRoute( path, '/': builder, (context, state) => const LandingPage(), ): GoRoute( path, '/info': builder, (context, state) => const InfoPage(), ), ]; ); }

I had the same problem and above is how i handle it我遇到了同样的问题,以上是我的处理方式

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';

Future<void> startingServices() async {
  await Future.delayed(const Duration(seconds: 40));
}

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      routerConfig: router,
    );
  }
}

class BeforeHome extends StatelessWidget {
  const BeforeHome({super.key});
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: startingServices(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          return const Home();
        } else {
          return const SplashSreen();
        }
      },
    );
  }
}

class Home extends StatelessWidget {
  const Home({super.key});
  @override
  Widget build(BuildContext context) {
    return const Material(
      child: Text("Home"),
    );
  }
}

class SplashSreen extends StatelessWidget {
  const SplashSreen({super.key});

  @override
  Widget build(BuildContext context) {
    
    return Material(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: const <Widget>[
          Text(
            "Initialization...",
            style: TextStyle(
              fontSize: 32,
              fontWeight: FontWeight.bold,
            ),
          ),
          
        ],
      ),
    );
  }
}

final router = GoRouter(
  routes: [
    GoRoute(
        path: '/',
        builder: (context, state) => const BeforeHome(),
        routes: [
          GoRoute(
            path: 'home',
            builder: (context, state) => const Home(),
          )
        ])
  ],
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 'firebase/main.dart':断言失败 - 'firebase/main.dart': Failed assertion 如何将 If 语句添加到 main.dart 文件 - How Add a If statement to main.dart file Flutter Navigator.of(context).pushReplacementNamed 抛出:“未处理的异常:Null 检查运算符用于 null 值”在 main.dart - Flutter Navigator.of(context).pushReplacementNamed throws :"Unhandled Exception: Null check operator used on a null value" on main.dart Flutter/Dart 返回 '_Future 的实例<string> ' 而不是实际的字符串值</string> - Flutter/Dart returning Instance of '_Future<String>' instead the actual String Value Dart:我如何初始化 class,以便在初始化时通过返回未来的 function 填充其属性之一? - Dart: how do I initialize a class such that one of its properties is filled upon initialization via a function that returns a future? 如何在 Dart 中使用 await 而不是 .then() - How to use await instead of .then() in Dart flutter / dart 错误:参数类型 'Future<file> ' 不能分配给参数类型 'File'</file> - flutter / dart error: The argument type 'Future<File>' can't be assigned to the parameter type 'File' 发生异常。 ArgumentError(无效参数:“未来”的实例<dynamic> ') Flutter Dart</dynamic> - Exception has occurred. ArgumentError (Invalid argument: Instance of 'Future<dynamic>') Flutter Dart 使用未来 presto 版本的 function - Use function from future presto version dart/flutter 从 Future.wait 中投射动态列表导致类型 'List<dynamic> ' 不是类型 'List 的子类型<customclass> '</customclass></dynamic> - dart/flutter casting dynamic list from Future.wait causing type 'List<dynamic>' is not a subtype of type 'List<CustomClass>'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM