无法将该叠加层窗口小部件标记为需要构建,因为该框架已在构建窗口小部件的过程中

时间:2019-08-22 08:34:56

标签: flutter

我有关注的应用程序:

class MyAppState extends State<MyApp>
{
  TenderApiProvider _tenderApiProvider = TenderApiProvider();

  Future init() async {
     await _tenderApiProvider.getToken();  
  }
  MyAppState()
  {
    init();
  }

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(builder: (_) => _tenderApiProvider),
      ],
      child: MaterialApp(
        title: "My App",
        routes: {
          '/': (context) => HomePage(),
          '/splash-screen': (context) => SplashScreen(),
          '/result_table': (context) => ResultDataTable(),
        }

      ),
    );
  }

}

我需要先绘制SplashScreen开头的HomePage当前代码。

在初始屏幕中,加载所有数据后,我需要切换到HomePage。这是代码:

  Widget build(BuildContext context) {
    TenderApiProvider apiProv = Provider.of<TenderApiProvider>(context);
    return StreamBuilder(
        stream: apiProv.resultController,
        builder: (BuildContext context, AsyncSnapshot snapshot) {   
        //...
        if(apiProv.apiKeyLoadingState ==  ApiKeyLoadingState.Done && apiProv.regionsLoadingState == RegionsLoadingState.Done)
        {
         Navigator.of(context).pushNamed("/"); // Should it be placed in Build??
        }
        });
    }

您能帮我演示在应用开始SplashScreen处绘制,然后从其切换到HomePage吗?

2 个答案:

答案 0 :(得分:1)

您需要将SplashScreen()包装在StatefulWidget中,以便可以在initState()中获取数据。将fetch()逻辑包装在SchedulerBinding.instance.addPostFrameCallback()内以访问BuildContext内的initState()很重要。而且,这样一来,您就可以避免与在实际构建时被破坏的RenderObject发生冲突。

下面是一个完整的最小示例。

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Wrapper(),
    );
  }
}


class Wrapper extends StatefulWidget {
  @override
  _WrapperState createState() => _WrapperState();
}

class _WrapperState extends State<Wrapper> {

  @override
  void initState() {
    super.initState();
    SchedulerBinding.instance.addPostFrameCallback((_) {
      // fetch data
      Navigator.of(context).pushNamed('/');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SplashScreen(),
    );
  }
}

答案 1 :(得分:0)

我使用splashScreen

UsefulPackage.net472.dll