2017-07-25 84 views
0

我用這個抽屜每個活動:抽屜避免無限活動創造

final MyDrawer _drawer = new MyDrawer(); 

class MyDrawer extends StatefulWidget { 
    @override 
    _MyDrawerState createState() => new _MyDrawerState(); 
} 

class _MyDrawerState extends State<MyDrawer> { 
    @override 
    Widget build(BuildContext context) { 
    return new Drawer(
     child: new ListView(
      children: <Widget> [ 
      new DrawerHeader(
       child: new Text("Header"), 
      ), 
      new ListTile(
       leading: new Icon(Icons.home), 
       title: new Text("Home"), 
       onTap:() { 
       Navigator.popAndPushNamed(context, "/"); 
       }, 

      ), 
      new ListTile(
       leading: new Icon(Icons.android), 
       title: new Text("Another Page"), 
       onTap:() { 
        Navigator.popAndPushNamed(context, AnotherPage.routeName); 
       }, 

      ),new ListTile(
       leading: new Icon(Icons.email), 
       title: new Text("Third Page"), 
       onTap:() { 
        Navigator.popAndPushNamed(context, ThirdPage.routeName); 
       } 
      ) 
      ] 
    ), 
    ); 
    } 
} 

每一頁是有狀態的小部件,它們共享相同的抽屜:

drawer: _drawer 

我正在尋找一種方式來只有一個活動實例,而不是每次單擊菜單項時創建一個新活動,我試過了:

ThirdPage.routeName: (BuildContext context) => 
     _thirdPage == null ? _thirdPage = new ThirdPage(title: "Third Page") : _thirdPage 

是否可以根據當前活動調整抽屜實例?

回答

0

我想你試圖實現單例類,即類只有一個實例。

一個Singleton類的一個實例:

class MyDrawer extends StatefulWidget{ 
    static final MyDrawer _drawer = new MyDrawer._internal(); 

    factory MyDrawer() { 
    return _drawer; 
    } 

    MyDrawer._internal(); 

    @override 
    Widget build(BuildContext context){ 
    return new Text("Drawer") 
    } 
} 

其他方式來實現鏢單例類,你可以看看答案here

希望有幫助!