Flutter:无法在AppDrawer中重用视图

时间:2018-10-15 17:01:26

标签: dart flutter flutter-layout

File:homepage.dart

class _HomePageState extends State<HomePage> {
var _scaffoldBody;
var _scaffoldTitle;

@override
initState() {
    _scaffoldTitle=new Text("Wall");
    _scaffoldBody=new Center(child:CircularProgressIndicator());
}


@override
Widget build(BuildContext context) {
return Scaffold(

    drawer: new Drawer(
      child: ListView(

        padding: EdgeInsets.zero,
        children: <Widget>[
          DrawerHeader(
            child: Text('Drawer Header'),
            decoration: BoxDecoration(
                color:Theme.of(context).accentColor,
            ),
          ),
          ListTile(
            title: Text('Home'),
            onTap: () {

              setState(() {
                _scaffoldTitle=new Text("Home");
                _scaffoldBody=new Text("Home Page");
              });

              Navigator.pop(context);
            },
          ),
          ListTile(
            title: Text('MenuItem1'),
            onTap: () {

              setState(() {
                _scaffoldTitle=new Text("1st Menu");
                _scaffoldBody=new TestPage("Page 1");
              });

              Navigator.pop(context);
            },
          ),
          ListTile(
            title: Text('MenuItem2'),
            onTap: () {

              setState(() {
                _scaffoldTitle=new Text("2nd Item");
                _scaffoldBody=new TestPage("Page 2");
              });

              Navigator.pop(context);
            },
          ),
        ],
      ),
    ),
    appBar: new AppBar(

      title: _scaffoldTitle,
      elevation: 2.0,
      actions: <Widget>[
      ],
    ),
    body:_scaffoldBody,

);

}

文件:TestPage.dart

import 'package:flutter/material.dart';
class TestPage extends StatefulWidget{
  final String rollNumber;
  TestPage(this.rollNumber);

  @override
  TestPageState createState() => new TestPageState(rollNumber);

}
class TestPageState extends State<TestPage>{
  String rollNumber;
  TestPageState(this.rollNumber);
  @override
  Widget build(BuildContext context) {
    return new  Text(rollNumber);
  }

}

输出:

  • 当我从抽屉中选择“主页”时,它显示为“主页”

  • 然后我选择:“ MenuItem1”显示为“ Page 1”

  • 然后我选择:“ MenuItem2”显示相同的“ Page 1”(意外)

  • 然后我选择:“主页”显示为“主页”

  • 然后我选择了“ MenuItem2”,它正确显示为“ Page 2”

  • 然后我选择:“ MenuItem1”显示为“ Page 2”(意外)

无法解决。卡住了!!任何解决方案表示赞赏。在此先感谢!

3 个答案:

答案 0 :(得分:0)

如下更新您的TestPart.dart:

import 'package:flutter/material.dart';
class TestPage extends StatefulWidget{
  final String rollNumber;
  TestPage(this.rollNumber);

  @override
  TestPageState createState() => new TestPageState();

}
class TestPageState extends State<TestPage>{
  @override
  Widget build(BuildContext context) {
    return new  Text(widget.rollNumber);
  }

}

答案 1 :(得分:0)

我的StudentPage班

import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';
import 'calendar_utils.dart';
import 'dart:async';
final mainReference = FirebaseDatabase.instance.reference();
class StudentPage extends StatefulWidget{
  final String rollNumber;
  StudentPage(this.rollNumber);

  @override
  StudentPageState createState() => new StudentPageState(rollNumber);

}
class StudentPageState extends State<StudentPage>{
  final String currentRoll,currentYear="2018-19";
  StudentPageState(this.currentRoll);


  List<String> academicMonth=["June","July","August","September","October","November","December",
                              "January","February","March","April","May"];





  int firstHalfYear=2018,secondHalfYear=2019;

  List<Widget> _monthListArray=[new ListTile(title:new Text("Academic Year",style: new TextStyle(fontWeight: FontWeight.bold,fontSize: 20.0),),)];
  List<Widget> _listView;

  int _no_of_working=0;
  int _no_of_present=0;
  @override
  void initState() {
    // TODO: implement initState


    _listView=[new Center(
      child: new CircularProgressIndicator(),
    )];
    _loadMonths();

  }


  @override
  Widget build(BuildContext context) {
    return new RefreshIndicator(child: new ListView(

      children: _listView,
    ), onRefresh: _loadMonths);
  }

  Future<Null> _loadMonths() async {


    _listView.clear();
    await mainReference.child("XXXX").child("attendance").child(
        widget.rollNumber).child(currentYear).once().then((
        DataSnapshot dataSnapshot) {
      try {

        int monthIndex=5;                                             //monthIndex starts from June
        for(var month in academicMonth){
          debugPrint("Month:"+month);
          monthIndex=(monthIndex+1)%12;           //month index cycles throughout 1-12
          if(monthIndex==0) monthIndex=12;
          List<Widget> _daysList=[];
          _monthListArray.add(new Padding(padding: EdgeInsets.all(16.0),child: new Text(month+" "+(monthIndex<6?secondHalfYear:firstHalfYear).toString(),style: new TextStyle(color: Colors.black87,fontWeight: FontWeight.bold,fontSize: 20.0),),));                       //initializing the month
          _monthListArray.add(new Padding(padding: EdgeInsets.only(top: 10.0,bottom: 10.0),child:
          new Row(children: <Widget>[
            new Expanded(
              child: new Center(child: new Text("S",style: new TextStyle(fontWeight: FontWeight.bold),),),
            ),
            new Expanded(
              child: new Center(child: new Text("M",style: new TextStyle(fontWeight: FontWeight.bold),),),
            ),
            new Expanded(
              child: new Center(child: new Text("T",style: new TextStyle(fontWeight: FontWeight.bold),),),
            ),
            new Expanded(
              child: new Center(child: new Text("W",style: new TextStyle(fontWeight: FontWeight.bold),),),
            ),
            new Expanded(
              child: new Center(child: new Text("T",style: new TextStyle(fontWeight: FontWeight.bold),),),
            ),
            new Expanded(
              child: new Center(child: new Text("F",style: new TextStyle(fontWeight: FontWeight.bold),),),
            ),
            new Expanded(
              child: new Center(child: new Text("S",style: new TextStyle(fontWeight: FontWeight.bold),),),
            ),

          ],),));
          debugPrint(monthIndex.toString());
          int freeSpace=CalendarUtils(1,monthIndex,monthIndex<6?secondHalfYear:firstHalfYear).getDayFromDate();
          debugPrint("FreeSpace---"+freeSpace.toString());
          if(freeSpace!=0){

            for (var i = 0; i < freeSpace; i++) {
              _daysList.add(new Text(""));
            }
          }
          debugPrint(monthIndex.toString());
          var year=monthIndex<6?secondHalfYear:firstHalfYear;
          debugPrint("Year"+year.toString());
          debugPrint("Forloop limit:"+CalendarUtils(1,monthIndex,monthIndex<6?firstHalfYear:secondHalfYear).numberOfDays().toString());
          for(var day=1;day<=CalendarUtils(1,monthIndex,monthIndex<6?secondHalfYear:firstHalfYear).numberOfDays();day++){

            try {
              //debugPrint(day.toString()+":"+dataSnapshot.value[month][day].toString());
              if (CalendarUtils(day, monthIndex,
                  monthIndex < 6 ? secondHalfYear: firstHalfYear)
                  .getDayFromDate() != 0){
                if (dataSnapshot.value[month][day].toString() == "1") {
                      _no_of_working++;
                      _no_of_present++;
                      _daysList.add(
                          new Padding(padding: EdgeInsets.only(left: 10.0,right: 10.0,top: 2.0,bottom: 2.0),
                            child: new Container(
                              alignment: Alignment.center,
                              width: 30.0,
                              height: 30.0,
                              decoration: new BoxDecoration(
                                  borderRadius: new BorderRadius.all(new Radius.circular(50.0)),
                                  color: Colors.green),
                              child: new Text(
                                day.toString(),
                                style: new TextStyle(color: Colors.white),
                              ),
                            ),
                          )
                      );
                }

                else if (dataSnapshot.value[month][day].toString() == "0"){
                  _no_of_working++;
                  _daysList.add(
                      new Padding(padding: EdgeInsets.only(left: 10.0,right: 10.0,top: 2.0,bottom: 2.0),
                      child: new Container(
                        alignment: Alignment.center,
                        width: 30.0,
                        height: 30.0,
                        decoration: new BoxDecoration(
                            borderRadius: new BorderRadius.all(new Radius.circular(50.0)),
                            color: Colors.redAccent),
                        child: new Text(
                          day.toString(),
                          style: new TextStyle(color: Colors.white),
                        ),
                      ),
                      )
                  );
                }
                else {

                  _daysList.add(
                      new Padding(padding: EdgeInsets.only(left: 10.0,right: 10.0,top: 2.0,bottom: 2.0),
                        child: new Container(
                          alignment: Alignment.center,
                          width: 30.0,
                          height: 30.0,
                          decoration: new BoxDecoration(
                              borderRadius: new BorderRadius.all(new Radius.circular(50.0)),
                              ),
                          child: new Text(
                            day.toString(),
                            style: new TextStyle(color: Colors.black),
                          ),
                        ),
                      )
                  );
                }
            }else {
                _daysList.add(
                    new Center(child: new Text(day.toString(), style:
                    new TextStyle(color: Colors.black45),)));
              }
            }catch (e){
              _daysList.add(new Center(child:new Text(day.toString(),style:
              new TextStyle(color: Colors.black),) ));
            }
          }

            Widget _daysGrid=new GridView.count(crossAxisCount: 7,
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
              childAspectRatio: 1.5,
            children: _daysList,
          );
          _monthListArray.add(_daysGrid);
        }

      }catch(e){}
      _monthListArray.add(new Text((_no_of_present/_no_of_working).toString()));
    });
    this.setState((){
      _listView=_monthListArray;
    });
  }
}

答案 2 :(得分:0)

我的HomePage.dart

import 'package:flutter/material.dart';
import 'package:smart_school_parent/TestPage.dart';
import 'package:smart_school_parent/attendance.dart';
import 'package:smart_school_parent/post.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:smart_school_parent/auth.dart';
import 'dart:async';


class HomePage extends StatefulWidget {
  final BaseAuth auth;
  final VoidCallback onSignOut;
  HomePage({Key key, this.auth, this.onSignOut}) : super(key: key);
  @override
  _HomePageState createState() => new _HomePageState(this.auth);
}

class _HomePageState extends State<HomePage> {
  final mainReference = FirebaseDatabase.instance.reference();

  List<PostData> post_list = new List();


  var _scaffoldBody;
  var _loading;
  var _currentYear;
  var _scaffoldTitle;
  List<Widget> _childrenList=[new Text("Profiles",textAlign: TextAlign.left,style: new TextStyle(fontWeight: FontWeight.bold),)];

  BaseAuth auth;

  _HomePageState(this.auth);

  @override
  initState() {

    //_children=updateChildren();
    _updateChildren();
    getList();
    _loading=true ;
    _scaffoldTitle=new Text("Wall");
    _scaffoldBody=new Center(child:CircularProgressIndicator());
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(

        drawer: new Drawer(
          child: ListView(
            // Important: Remove any padding from the ListView.
            padding: EdgeInsets.zero,
            children: <Widget>[
              DrawerHeader(
                child: Text('XXXXx'),
                decoration: BoxDecoration(
                    color:Theme.of(context).accentColor,
                ),
              ),
              ListTile(
                title: Text('Wall'),
                onTap: () {
                  setState(() {
                    _scaffoldTitle=new Text("Wall");
                    _scaffoldBody=new RefreshIndicator(child: _loadWall(), onRefresh: getList);
                  });

                  Navigator.pop(context);
                },
              ),
             Column(
               children: _childrenList,
             ),
            ],
          ),
        ),
        appBar: new AppBar(

          title: _scaffoldTitle,
          elevation: 2.0,
          actions: <Widget>[
          ],
        ),
        body:_scaffoldBody,

    );

  }

  Future <Null> getList() async {
    await mainReference.child("NISE-Coimbatore").child("posts").once().then((DataSnapshot dataSnapshot) {
      this.setState(() {
        post_list.clear();
        if(dataSnapshot.value!=null){
        for (var value in dataSnapshot.value.values) {
          post_list.add(new PostData.fromJson(value));
          //debugPrint(value.toString());
        }
        }else{
          this.setState((){

          });
        }
      });
    });
    setState(() {
      _scaffoldBody=new RefreshIndicator(child: _loadWall(), onRefresh: getList);
    });
  }
  Widget _loadWall(){
    return Stack(
      children: <Widget>[

        new ListView.builder(itemBuilder: (BuildContext context,int index){
          return new Post(post_list[index].image,post_list[index].title,post_list[index].content);
        },
          itemCount: post_list == null ? 0 : post_list.length,)
      ],
    );
  }

   _updateChildren() async {
    _currentYear= await mainReference.child("attendance").child("currentYear").once();
    await auth.currentUser().then((String userId) async{

      mainReference.child("NISE-Coimbatore").child("parents").child(userId).child('children').once().then((DataSnapshot dataSnapshot){
        for (var value in dataSnapshot.value){
          this.setState((){
            _childrenList.add(
              new Padding(
                padding: EdgeInsets.only(left: 25.0),
                child:  ListTile(
                  title: Text(value.toString()),
                  onTap: () {

                    super.setState(() {

                      _scaffoldTitle=new Text(value.toString());
                      this._scaffoldBody=new StudentPage(value.toString());

                    });

                    Navigator.pop(context);
                  },
                ),
              ),

            );
          });

          //debugPrint("Childrrncount::"+value.toString());
        }
      });
    });
   }



}
class PostData{
  String title;
  String content;
  String image;

  PostData(this.title, this.content, this.image);

  PostData.fromJson(var value) {
    this.title = value['title'];
    this.content = value['content'];
    this.image = value['image'];
  }
}

_childrenList具有两个元素。 datasnapshot.values具有[15505,15501]两个卷号

firebase的两个滚动号都出现在抽屉框上,并在点击时预期显示StudentPage(15501.tostring())或StudentPage(15505.tostring())

如果从抽屉中选择“ Wall”,然后选择任何“ rollNumbers”,则可以按预期工作

如果我从抽屉中的rollNumbers之一切换到其他rollNumber,则无法正常工作。

类似于我的第一篇文章。仅_scaffoldTitle会相应地更改。