如何在Flutter中实现动态窗口小部件路由?

时间:2019-01-19 20:48:11

标签: dart flutter

我正在将路由添加到我的Flutter应用程序中,我想在我的所有路由中重复使用一些常见的小部件。

例如,AppBarDrawer实例应在顶层视图中定义,而路由视图应在包含的小部件(图像中的黄色部分)中

是否受支持??我目前发现的所有“颤振路由”参考都展示了整个视图的替换=>每条路径的通用小部件的不同实例。

enter image description here

void redirect(BuildContext context, name) {
  Navigator.of(context).pushNamed(name);
}

getCommonDrawer(context) {
  return Drawer(
    child: ListView(
      padding: EdgeInsets.zero,
      children: <Widget>[
        DrawerHeader(
          child: Text('header'),
          decoration: BoxDecoration(
            color: Colors.greenAccent,
          ),
        ),
        ListTile(
          title: Text('foo'),
          onTap: () {
            Navigator.pop(context);
          },
        ),
        ListTile(
          title: Text('bar'),
          onTap: () {
            Navigator.pop(context);
          },
        ),
      ],
    ),
  );
}

class Screen1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Screen 1"),
      ),
      drawer: getCommonDrawer(context),
      body: new Center(
        child: new Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            new RaisedButton(
              onPressed: () {
                redirect(context, "/screen2");
              },
              child: new Text("screen2"),
            )
          ],
        ),
      ),
    );
  }
}

class Screen2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Screen 2"),
      ),
      drawer: getCommonDrawer(context),
      body: new Center(
        child: new Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            new RaisedButton(
              onPressed: () {
                redirect(context, "/screen1");
              },
              child: new Text("screen1"),
            )
          ],
        ),
      ),
    );
  }
}


void main() { // 1
  runApp( // 2
    new MaterialApp( //3
      home: new Screen1(), //4
      routes: <String, WidgetBuilder> { //5
        '/screen1': (BuildContext context) => new Screen1(), //6
        '/screen2' : (BuildContext context) => new Screen2() //7
      },
    )
  );
}

0 个答案:

没有答案