如何使自定义窗口小部件在多个屏幕中保持一致

时间:2019-04-14 12:57:41

标签: flutter

我正在制作一个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 
                ),
              ],
            )


    );
  }

上面的代码在屏幕底部有一个定位的小部件,我想在多个屏幕上保持相同?我该如何实现?我了解android,在那种情况下我可以实现使用片段事务,但是在这里我必须在所有屏幕上都保留底部定位的小部件,而问题是在更改屏幕底部位置小部件后消失了一段时间,但我希望该底部小部件保持静态,仅更改屏幕,而不更改底部的小部件

3 个答案:

答案 0 :(得分:0)

您可以做两件事之一

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,
      .......
    );
  }

}

然后以CommonBottom()的形式在您的所有页面中使用它

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

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

答案 1 :(得分:0)

好吧,除非您在每个页面中都实现了它,否则它并不是对所有页面都是静态的,为此,您需要在该类存在的地方导入文件并直接使用它。

import 'packages/mycommonclass.dart';

,然后将其放置在其他页面的同一位置。

答案 2 :(得分:0)

实现这一点的一种方法是在 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),
    );
  }
}

这将在所有屏幕中呈现小部件,屏幕之间的过渡动​​画不会弄乱它,您可以像往常一样在页面中自由使用其他 Scaffold。