1

Flutter:第一次第二页传入参数的值为null。如果我进行热重载,则此值不为空。

也许是因为 TabBar,但是在使用 TabBar 时如何第一次获得真正的价值?

请帮我找到解决问题的方法

第一页。idBou 在这里不为空

class BoutiquePage extends StatefulWidget {
  int idboutique;

  BoutiquePage({this.idboutique});

  @override
  _BoutiquePageState createState() => _BoutiquePageState();
}

class _BoutiquePageState extends State<BoutiquePage> {

  SharedPreferences sharedPreferences;
 
  
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

  String idBou ;
  String nomAbon ;
  String prenomAbon ;
  String telAbon ;
  String addAbon;
  String nomBou;
  String ville;
  String pays;

  String lien_photo_bout;


  bool _isLoading = false;


  String _errorText;

  get article_afficher333 => article_afficher333;

  @override
  void initState() { 
    setState((){ 
      getShaerInstance();
    }); 
    super.initState();
  }
  getShaerInstance() async {
    sharedPreferences = await SharedPreferences.getInstance(); 
  }


    Future<Map<String, dynamic>> getAllStoreInfoData2(int idboutique) async {
      final response = await http.get(http://xxxxxx.com+"boutique/home?id_bout="+idboutique.toString()); 
      if (response.statusCode == 200) {
        final jsonResponse = json.decode(response.body);
        BoutiqueData myData = new BoutiqueData.fromJson(jsonResponse);
        
        Map<String, dynamic> boutiqueinfodata = Map();
        boutiqueinfodata["boutiqueType"] = myData.v_boutique.typeBoutique; 
        return boutiqueinfodata;

      } else {
        throw Exception("Failed to load Data");
      }
    }

   
  //SharedPreferences

  @override
  Widget build(BuildContext context) {

    Widget myboutiqueinfodata = FutureBuilder(
      future: getAllStoreInfoData2(widget.idboutique),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          Map<String, dynamic> alldata = snapshot.data;          
          typeBoutique = alldata["boutiqueType"];        
          List<ListeInfoBoutique> boutiqueInfoData = alldata["boutiqueInfoData"];   
           
            for (var i = 0; i < boutiqueInfoData.length; i++) {
              idBou = boutiqueInfoData[i].idBou;
              nomAbon = boutiqueInfoData[i].nomAbon;
              prenomAbon = boutiqueInfoData[i].prenomAbon;
              telAbon = boutiqueInfoData[i].telAbon;
              addAbon = boutiqueInfoData[i].addAbon; 
            }

            return   Scaffold(
                body: ListView(
                  children: <Widget>[
                     
                  ],
                ),
              );



        }else if (snapshot.hasError) {
          return Container(
            child: Center(
              child: Text(AppLocalizations.of(context)
                      .translate('_MSG_ER_CONNEXION_CHARGE_DATA'), 
                                  style: TextStyle(
                                    fontSize: 18,
                                    fontFamily: 'Questrial'
                                  ),),
            ),
          );
        }
        return new Center(
          child: CircularProgressIndicator(),
        );
      });

    return DefaultTabController(
      length: 5,
      child: Scaffold(
        key: _scaffoldKey,
        appBar: AppBar(
            title: Text(AppLocalizations.of(context)
                        .translate('_MY_STORE'), style: TextStyle(color: Colors.white, fontFamily: "Questrial"),),
            iconTheme: new IconThemeData(color: Color(0xFFFFFFFF)),
            actions: <Widget>[

              //
            ],
            bottom: TabBar(
              isScrollable: true,
              indicatorColor: Colors.white,
              indicatorWeight: 5.0,
              //onTap: (){},
              tabs: <Widget>[
                Tab(
                  child: Container(
                    child: Text(AppLocalizations.of(context)
                        .translate('_STORE_INFO'), style: TextStyle(color: Colors.white, fontSize: 18.0, fontFamily: 'Questrial'),),
                  ),
                ),
                Tab(
                  child: Container(
                    child: Text(AppLocalizations.of(context)
                        .translate('_MY_ARTICLES'), style: TextStyle(color: Colors.white, fontSize: 18.0, fontFamily: 'Questrial'),),
                  ),
                ),
              ],
            ),
        ),
        body: TabBarView(
          children: <Widget>[
                myboutiqueinfodata, 
                MesArticles(idboutique: idBou),
              ],
            ),
          ),
        );
      }

    }

第一次打印 null 并在热重载后打印的 Secode 页面不为 null


class MesArticles extends StatefulWidget {
  final String idboutique;
  const MesArticles({Key key, this.idboutique}) : super(key: key);

  @override
  _MesArticleState createState() => _MesArticleState();
}

class _MesArticleState extends State<MesArticles> {

  @override
  Widget build(BuildContext context) {
   print(widget.idboutique.toString()); // it print null for fist time. After hot reload it become not null
    return Scaffold(
      body: Text(widget.idboutique.toString()), //<== it print null for fist time.
    );
  }
}
4

1 回答 1

1

试试这个代码。我认为 Future builder 是它抛出 null 的原因。

class BoutiquePage extends StatefulWidget {
  int idboutique;

  BoutiquePage({this.idboutique});

  @override
  _BoutiquePageState createState() => _BoutiquePageState();
}

class _BoutiquePageState extends State<BoutiquePage> {

  SharedPreferences sharedPreferences;
 
  
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

  String idBou ;
  String nomAbon ;
  String prenomAbon ;
  String telAbon ;
  String addAbon;
  String nomBou;
  String ville;
  String pays;

  String lien_photo_bout;


  bool _isLoading = false;
  bool _isLoaded = false;
  bool _isError = false;


  String _errorText;

  get article_afficher333 => article_afficher333;

  @override
  void initState() { 
    setState((){ 
      getShaerInstance();
    }); 
    super.initState();
  }
  getShaerInstance() async {
    sharedPreferences = await SharedPreferences.getInstance(); 
  }


    Future<Map<String, dynamic>> getAllStoreInfoData2(int idboutique) async {
      final response = await http.get("http://xxxxxx.com/" + "boutique/home?id_bout="+idboutique.toString()); 
        if (response.statusCode == 200) {
        final jsonResponse = json.decode(response.body);
        BoutiqueData myData = new BoutiqueData.fromJson(jsonResponse);
        
        Map<String, dynamic> boutiqueinfodata = Map();
        boutiqueinfodata["boutiqueType"] = myData.v_boutique.typeBoutique; 
        return boutiqueinfodata;

      } else {
        throw Exception("Failed to load Data");
      }
    }

   
  //SharedPreferences

  initDataFromServer(idboutique) async {

    try {


    var alldata = await  getAllStoreInfoData2(idboutique);         
          var typeBoutique = alldata["boutiqueType"];        
          List<ListeInfoBoutique> boutiqueInfoData = alldata["boutiqueInfoData"];   
           
            for (var i = 0; i < boutiqueInfoData.length; i++) {
              idBou = boutiqueInfoData[i].idBou;
              nomAbon = boutiqueInfoData[i].nomAbon;
              prenomAbon = boutiqueInfoData[i].prenomAbon;
              telAbon = boutiqueInfoData[i].telAbon;
              addAbon = boutiqueInfoData[i].addAbon; 
            }

        setState(() {
          _isLoaded = true;
          _isLoading = false;
          _isError = false;
        });

    } catch (e) {
      print(e);
      setState(() {
        _isLoaded = true;
        _isLoading = true;
        _isError = true;
      });
    }
    
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoaded == false && _isLoading == false) {
      _isLoading = true;
      initDataFromServer(widget.idboutique);
    }

    return DefaultTabController(
      length: 5,
      child: Scaffold(
        key: _scaffoldKey,
        appBar: AppBar(
            title: Text(AppLocalizations.of(context)
                        .translate('_MY_STORE'), style: TextStyle(color: Colors.white, fontFamily: "Questrial"),),
            iconTheme: new IconThemeData(color: Color(0xFFFFFFFF)),
            actions: <Widget>[

              //
            ],
            bottom: TabBar(
              isScrollable: true,
              indicatorColor: Colors.white,
              indicatorWeight: 5.0,
              //onTap: (){},
              tabs: <Widget>[
                Tab(
                  child: Container(
                    child: Text(AppLocalizations.of(context)
                        .translate('_STORE_INFO'), style: TextStyle(color: Colors.white, fontSize: 18.0, fontFamily: 'Questrial'),),
                  ),
                ),
                Tab(
                  child: Container(
                    child: Text(AppLocalizations.of(context)
                        .translate('_MY_ARTICLES'), style: TextStyle(color: Colors.white, fontSize: 18.0, fontFamily: 'Questrial'),),
                  ),
                ),
              ],
            ),
        ),
        body: TabBarView(
          children: <Widget>[
                _isLoaded == false ? Center(
          child: CircularProgressIndicator(),
        ): (_isError == false ? Text("Your data Loaded") : Text("Error")),
        
                _isLoaded == false ? Center(
          child: CircularProgressIndicator(),
        ): (_isError == false ? MesArticles(idboutique: idboutique) : Text("Error")), 
                
              ],
            ),
          ),
        );
      }

    }
class MesArticles extends StatefulWidget {
  final String idboutique;
  const MesArticles({Key key, this.idboutique}) : super(key: key);

  @override
  _MesArticleState createState() => _MesArticleState(idboutique: idboutique);
}

class _MesArticleState extends State<MesArticles> {
  final String idboutique;

  _MesArticleState({this.idboutique});

  @override
  Widget build(BuildContext context) {
   print(widget.idboutique.toString()); // it print null for fist time. After hot reload it become not null
    return Scaffold(
      body: Text(widget.idboutique.toString()),
    );
  }
}
于 2020-08-28T15:27:37.280 回答