Flutter: невозможно повторно использовать представления в appdrawer - PullRequest
0 голосов
/ 15 октября 2018

Файл: 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);
  }

}

Вывод:

  • Когда я выбрал: «Home» из ящика, он показывает «Home Page»

  • Затем я выбрал: «MenuItem1», он показал «Page 1»

  • Затем я выбрал: «MenuItem2», он показал то же самое «Страница 1» (неожиданно)

  • Затем я выбрал: «Домой» он показал «Домашняя страница»

  • Затем я выбрал: «MenuItem2», он правильно показывался как «Страница 2»

  • Затем я выбрал: «MenuItem1», он показал «Страница 2» (неожиданно)

не в состоянии решить эту проблему.Любые решения приветствуются.Заранее спасибо !!

Ответы [ 3 ]

0 голосов
/ 15 октября 2018

My StudentPage Class

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;
    });
  }
}
0 голосов
/ 15 октября 2018

My 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())

работает как положено, если выбрать «Стена» из ящика, а затем любое из «rollNumbers»

, это не работает, если я переключаюсь с одного из номеров RollNumbers на другой номер RollNumber вящик.

Похоже на мой первый пост.Соответственно изменяется только _scaffoldTitle.

0 голосов
/ 15 октября 2018

Обновите свой 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);
  }

}
...