如何在 flutter 中保持自定义小部件在多个屏幕上通用

Vip*_*bey 6 flutter

我正在制作一个颤振应用程序,其中我需要两个放置一个小部件,这对于多个屏幕来说很常见。这是屏幕一的构建方法的代码

  Widget build(BuildContext context) {

    return Scaffold(
      backgroundColor: app_color,
        body: _isLoading == false ? Stack(


          new Container(//used for whole screen ),
            Positioned(
              left: 0,
                    right: 0,
                    bottom: 0,
              //a bottom tab like which is common across screens
            ),

          ],
        )
      :
          //code to show progress indicator while loading data in background 
            Stack(
              children: <Widget>[
                Center(
                    child:Container(
                      height: 50,
                      width: 50,
                      child: CircularProgressIndicator(),
                    )
                ),
                Positioned(
                    left: 0,
                    right: 0,
                    bottom: 0,
                    //keep this to show bottom tab while loading 
                ),
              ],
            )


    );
  }
Run Code Online (Sandbox Code Playgroud)

上面的代码在屏幕底部有一个定位小部件,我想在多个屏幕上保持通用?我怎样才能实现它?我了解android,在这种情况下,我可以使用片段事务来实现,但在这里我必须在所有屏幕上保持底部定位的小部件,问题是在更改屏幕底部位置小部件后会消失一段时间,但我想要那个底部小部件保持静态并仅更改屏幕而不是底部定位的小部件

小智 6

实现此目的的一种方法是在 MaterialApp 小部件中自定义构建器。

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Test',
      home: TestPage(),
      initialRoute: "/test",
      builder: (context, child) {
        return Scaffold(
          body: Stack(
            children: [
              child!,
              Positioned(
                    left: 0,
                    right: 0,
                    bottom: 0,
              ),
            ],
          ),
        );
      },
      routes: routes(context),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

这将在所有屏幕中渲染小部件,并且屏幕之间的过渡动​​画不会弄乱它,并且您可以像平常一样在页面中自由使用其他支架。


Amm*_*tef 2

你可以做两件事之一

1-创建自定义小部件

创建一个名为的文件common_view.dart并将视图添加到其中

import 'package:flutter/material.dart';

class CommonBottom extends StatelessWidget {
  CommonBottom();

  @override
  Widget build(BuildContext context) {
    return Positioned(
      left: 0,
      right: 0,
      .......
    );
  }

}
Run Code Online (Sandbox Code Playgroud)

然后在所有页面中使用它CommonBottom()

2-将您的应用程序创建为单页应用程序

为您需要的每个页面创建一个有状态的小部件,并将其呈现在使用可见性小部件包裹的页面内。