Desapareciendo datos en aleteo en el cambio de página -- api campo con flutter campo con flutter-layout camp Relacionados El problema

disappearing data in flutter on page change


1
vote

problema

Español

Comencé la aplicación Flutter para aprender funciones API, pero estoy recibiendo este problema que es cuando cambio la página y vuelva a la página anterior, los datos que estaba mostrando se convierten en NULL en todas las páginas. Y no sé la razón detrás de esto.

a continuación es la imagen de cómo va -:

  1. ingrese la descripción de la imagen aquí
  2. ingrese la descripción de la imagen aquí
  3. ingrese la descripción de la imagen aquí
  4. ingrese la descripción de la imagen aquí

A continuación se muestra el código en el que recibo datos de una página a la página de inicio y lo estoy mostrando. y desaparece en el cambio de página -:

   import 'package:education/LogIn_SignUp/Log_In.dart'; import 'package:education/Screens/Profile_Screen.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'About_Scree.dart'; import 'Change_Password.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; import 'dart:async';       class homeView extends StatefulWidget{    var user_id;   var user_name;   var mobile_number;   var user_address;   var user_Email;   var coaching_id;   var coaching_name;   var coaching_address;   var primary_no;   var altnumber;   var coaching_email;      homeView({     this.user_id,this.user_name,this.mobile_number,this.user_address,this.coaching_id,this.coaching_name,     this.coaching_address,this.primary_no,this.altnumber,this.coaching_email,this.user_Email });    @override   State<StatefulWidget> createState() => homeViewState(); }    class homeViewState extends State<homeView> {     TextEditingController editingController = TextEditingController();    var showItemList = List<String>();   int count = 10;       var userid, username, mobilenumber, useraddress, userEmail, coachingid, coachingname, coachingaddress;   var primaryno, alt_number, coachingemail;    void setdata(){     setState(() {       userid = widget.user_id;       username = widget.user_name;       mobilenumber = widget.mobile_number;       useraddress = widget.user_address;       userEmail = widget.user_Email;       coachingid = widget.coaching_id;       coachingname = widget.coaching_name;       coachingaddress = widget.coaching_address;     });   }      @override   void initState(){     // showItemList.addAll(initList);     // getData();     setdata();     super.initState();   }     @override   void dispose() {     editingController.dispose();     super.dispose();   }    /// -----------------------------------------------------------------------------------------------------------------------------   ///                                           Main Build Function for the class.   /// -----------------------------------------------------------------------------------------------------------------------------     @override   Widget build(BuildContext context) {      return SafeArea(       child: Scaffold(         appBar: PreferredSize(           preferredSize: Size.fromHeight(90.0),           child: AppBar(             title: Padding(               padding: const EdgeInsets.only(top: 20),               child: Text(                 '$coachingname',//'${widget.coaching_name}',                 style: TextStyle(                   fontSize: 25.0,                   letterSpacing: 4.5,                   fontFamily: 'Sarif',                   fontWeight: FontWeight.w300,                   color: Colors.white,                 ),               ),             ),             backgroundColor: Colors.deepPurpleAccent,             centerTitle: true,             actions: <Widget>[               Column(                 children: [                   InkWell(                     child: new IconButton(                         icon: Padding(                           padding: const EdgeInsets.only(top: 20),                           child: Icon(Icons.exit_to_app),                         ),                         onPressed:(){                           Navigator.pushReplacement(context, MaterialPageRoute(                             builder: (context) => LoginPage(),                           ));                         }                     ),                     onTap: (){                       Navigator.pushReplacement(context, MaterialPageRoute(                         builder: (context) => LoginPage()                       ));                     },                   ),                 ],               ),             ],           ),         ),         drawer: Drawer(           child: Container(             padding: EdgeInsets.all(10),             child: ListView(               children: <Widget>[                  Container(                   height: 180,                   decoration: BoxDecoration(                     gradient: LinearGradient(colors: [                       Colors.purple.shade300,                       Colors.deepPurpleAccent.shade200,                     ]),                   ),                   child: Column(                     children: [                        Padding(                         padding: const EdgeInsets.only(top: 45.0, bottom: 10),                         child: Card(                             shape: RoundedRectangleBorder(                               borderRadius: BorderRadius.circular(55),                             ),                             color: Colors.blue,                             child: Padding(                               padding: const EdgeInsets.all(10.0),                               child: Icon(Icons.perm_identity_outlined, color: Colors.white,size: 30),                             )                         ),                       ),                        Text(                         '$username',//'${widget.user_name}',                         style: TextStyle(                           color: Colors.white,                           fontSize: 24,                           letterSpacing: 2.5,                         ),                       ),                       ],                   ),                 ),                   ListTile(                   title: Text('Profile',                     style: TextStyle(                     fontSize: 17,                     fontWeight: FontWeight.w400,                     letterSpacing: 1.5,                   ),                   ),                   leading: Icon(Icons.person_pin, color: Colors.blue,),                   selectedTileColor: Colors.blue,                   onTap: (){                     Navigator.pushReplacement(context, MaterialPageRoute(                       builder: (context) => ProfilePage(                         user_id: userid, user_name:username, mobile_number:mobilenumber, user_address:useraddress,                         user_Email: userEmail,                       )                     ));                   },                 ),                  ListTile(                   title: Text('Change Password',                     style: TextStyle(                       fontSize: 17,                       fontWeight: FontWeight.w400,                       letterSpacing: 1.5,                     ),                   ),                   leading: Icon(Icons.security, color: Colors.blue,),                   selectedTileColor: Colors.blue,                   onTap: (){                     Navigator.pushReplacement(context, MaterialPageRoute(                       builder: (context) => ChangePassword()                     ));                   },                 ),                  ListTile(                   title: Text('About',                     style: TextStyle(                     fontSize: 17,                     fontWeight: FontWeight.w400,                     letterSpacing: 1.5,                   ),                 ),                   leading: Icon(Icons.info_outline, color: Colors.blue,),                   selectedTileColor: Colors.blue,                   onTap: (){                     Navigator.pushReplacement(context, MaterialPageRoute(                       builder: (context) => AboutScreen(                         coaching_id:coachingid, coaching_name:coachingname, coaching_address:coachingaddress,                         primary_no:primaryno, altnumber:alt_number, coaching_email:coachingemail                       )//coaching details                     ));                   },                 ),                  ListTile(                   title: Text(                     'Rate',                     style: TextStyle(                       fontSize: 17,                       fontWeight: FontWeight.w400,                       letterSpacing: 1.5,                     ),                   ),                   leading: Icon(Icons.star_border_outlined, color: Colors.blue,),                   selectedTileColor: Colors.blue,                   onTap: (){                    },                 ),                   Divider(                   color: Colors.red,                   thickness: 1,                 ),                   SizedBox(height: 10,),                  Text(                   'Contact Us',                   style: TextStyle(                     fontSize: 20,                     color: Colors.grey[800],                     letterSpacing: 1.5,                     fontWeight: FontWeight.w500,                   ),                 ),                  SizedBox(height: 10,),                  ListTile(                   title: Text('Share',                     style: TextStyle(                       fontSize: 17,                       fontWeight: FontWeight.w400,                       letterSpacing: 1.5,                     ),                   ),                   leading: Icon(Icons.share, color: Colors.blue,),                   selectedTileColor: Colors.blue,                   onTap: (){                    },                 ),                  ListTile(                   title: Text('Privacy Policy',                     style: TextStyle(                       fontSize: 17,                       fontWeight: FontWeight.w400,                       letterSpacing: 1.5,                     ),                   ),                   leading: Icon(Icons.privacy_tip, color: Colors.blue,),                   selectedTileColor: Colors.blue,                   onTap: (){                    },                 ),                  ListTile(                   title: Text(                     'LogOut',                     style: TextStyle(                       fontSize: 17,                       fontWeight: FontWeight.w400,                       letterSpacing: 1.5,                     ),                   ),                   leading: Icon(Icons.logout, color: Colors.blue,),                   selectedTileColor: Colors.blue,                   onTap: (){                     Navigator.pushReplacement(context, MaterialPageRoute(                       builder: (context) => LoginPage()                     ));                    },                 ),                  ],             ),           ),         ),         body: Container(),       ),     );   } }    

Los datos que estoy pasando a esta página es la siguiente::

  I/flutter ( 4512): {address: jaipur, jaipur, alt_number: 9865358577, coach_address: Gautam Budha nagar, noida, coach_id: 2, coach_name: SSG Coaching, coaching_email: SSG@gmail.com, mobile_number: 9999999999, primary_no: 9898557898, res: success, user_id: 3, user_mail: s@gmail.com, user_name: sagar, user_pass: sagar123}   

Ayuda, ya que no puedo rastrear el error o encontrar ninguna solución.

Original en ingles

I started the flutter app to learn API functions but I am getting this problem that is when I change the page and go back to the previous page the data that I was displaying becomes null on all the pages. and I don't know the reason behind this.

below is the image of how it goes -:

  1. enter image description here
  2. enter image description here
  3. enter image description here
  4. enter image description here

below is the code in which I am getting data from one page to the home page and I am displaying it. and it disappears on page change -:

 import 'package:education/LogIn_SignUp/Log_In.dart'; import 'package:education/Screens/Profile_Screen.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'About_Scree.dart'; import 'Change_Password.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; import 'dart:async';       class homeView extends StatefulWidget{    var user_id;   var user_name;   var mobile_number;   var user_address;   var user_Email;   var coaching_id;   var coaching_name;   var coaching_address;   var primary_no;   var altnumber;   var coaching_email;      homeView({     this.user_id,this.user_name,this.mobile_number,this.user_address,this.coaching_id,this.coaching_name,     this.coaching_address,this.primary_no,this.altnumber,this.coaching_email,this.user_Email });    @override   State<StatefulWidget> createState() => homeViewState(); }    class homeViewState extends State<homeView> {     TextEditingController editingController = TextEditingController();    var showItemList = List<String>();   int count = 10;       var userid, username, mobilenumber, useraddress, userEmail, coachingid, coachingname, coachingaddress;   var primaryno, alt_number, coachingemail;    void setdata(){     setState(() {       userid = widget.user_id;       username = widget.user_name;       mobilenumber = widget.mobile_number;       useraddress = widget.user_address;       userEmail = widget.user_Email;       coachingid = widget.coaching_id;       coachingname = widget.coaching_name;       coachingaddress = widget.coaching_address;     });   }      @override   void initState(){     // showItemList.addAll(initList);     // getData();     setdata();     super.initState();   }     @override   void dispose() {     editingController.dispose();     super.dispose();   }    /// -----------------------------------------------------------------------------------------------------------------------------   ///                                           Main Build Function for the class.   /// -----------------------------------------------------------------------------------------------------------------------------     @override   Widget build(BuildContext context) {      return SafeArea(       child: Scaffold(         appBar: PreferredSize(           preferredSize: Size.fromHeight(90.0),           child: AppBar(             title: Padding(               padding: const EdgeInsets.only(top: 20),               child: Text(                 '$coachingname',//'${widget.coaching_name}',                 style: TextStyle(                   fontSize: 25.0,                   letterSpacing: 4.5,                   fontFamily: 'Sarif',                   fontWeight: FontWeight.w300,                   color: Colors.white,                 ),               ),             ),             backgroundColor: Colors.deepPurpleAccent,             centerTitle: true,             actions: <Widget>[               Column(                 children: [                   InkWell(                     child: new IconButton(                         icon: Padding(                           padding: const EdgeInsets.only(top: 20),                           child: Icon(Icons.exit_to_app),                         ),                         onPressed:(){                           Navigator.pushReplacement(context, MaterialPageRoute(                             builder: (context) => LoginPage(),                           ));                         }                     ),                     onTap: (){                       Navigator.pushReplacement(context, MaterialPageRoute(                         builder: (context) => LoginPage()                       ));                     },                   ),                 ],               ),             ],           ),         ),         drawer: Drawer(           child: Container(             padding: EdgeInsets.all(10),             child: ListView(               children: <Widget>[                  Container(                   height: 180,                   decoration: BoxDecoration(                     gradient: LinearGradient(colors: [                       Colors.purple.shade300,                       Colors.deepPurpleAccent.shade200,                     ]),                   ),                   child: Column(                     children: [                        Padding(                         padding: const EdgeInsets.only(top: 45.0, bottom: 10),                         child: Card(                             shape: RoundedRectangleBorder(                               borderRadius: BorderRadius.circular(55),                             ),                             color: Colors.blue,                             child: Padding(                               padding: const EdgeInsets.all(10.0),                               child: Icon(Icons.perm_identity_outlined, color: Colors.white,size: 30),                             )                         ),                       ),                        Text(                         '$username',//'${widget.user_name}',                         style: TextStyle(                           color: Colors.white,                           fontSize: 24,                           letterSpacing: 2.5,                         ),                       ),                       ],                   ),                 ),                   ListTile(                   title: Text('Profile',                     style: TextStyle(                     fontSize: 17,                     fontWeight: FontWeight.w400,                     letterSpacing: 1.5,                   ),                   ),                   leading: Icon(Icons.person_pin, color: Colors.blue,),                   selectedTileColor: Colors.blue,                   onTap: (){                     Navigator.pushReplacement(context, MaterialPageRoute(                       builder: (context) => ProfilePage(                         user_id: userid, user_name:username, mobile_number:mobilenumber, user_address:useraddress,                         user_Email: userEmail,                       )                     ));                   },                 ),                  ListTile(                   title: Text('Change Password',                     style: TextStyle(                       fontSize: 17,                       fontWeight: FontWeight.w400,                       letterSpacing: 1.5,                     ),                   ),                   leading: Icon(Icons.security, color: Colors.blue,),                   selectedTileColor: Colors.blue,                   onTap: (){                     Navigator.pushReplacement(context, MaterialPageRoute(                       builder: (context) => ChangePassword()                     ));                   },                 ),                  ListTile(                   title: Text('About',                     style: TextStyle(                     fontSize: 17,                     fontWeight: FontWeight.w400,                     letterSpacing: 1.5,                   ),                 ),                   leading: Icon(Icons.info_outline, color: Colors.blue,),                   selectedTileColor: Colors.blue,                   onTap: (){                     Navigator.pushReplacement(context, MaterialPageRoute(                       builder: (context) => AboutScreen(                         coaching_id:coachingid, coaching_name:coachingname, coaching_address:coachingaddress,                         primary_no:primaryno, altnumber:alt_number, coaching_email:coachingemail                       )//coaching details                     ));                   },                 ),                  ListTile(                   title: Text(                     'Rate',                     style: TextStyle(                       fontSize: 17,                       fontWeight: FontWeight.w400,                       letterSpacing: 1.5,                     ),                   ),                   leading: Icon(Icons.star_border_outlined, color: Colors.blue,),                   selectedTileColor: Colors.blue,                   onTap: (){                    },                 ),                   Divider(                   color: Colors.red,                   thickness: 1,                 ),                   SizedBox(height: 10,),                  Text(                   'Contact Us',                   style: TextStyle(                     fontSize: 20,                     color: Colors.grey[800],                     letterSpacing: 1.5,                     fontWeight: FontWeight.w500,                   ),                 ),                  SizedBox(height: 10,),                  ListTile(                   title: Text('Share',                     style: TextStyle(                       fontSize: 17,                       fontWeight: FontWeight.w400,                       letterSpacing: 1.5,                     ),                   ),                   leading: Icon(Icons.share, color: Colors.blue,),                   selectedTileColor: Colors.blue,                   onTap: (){                    },                 ),                  ListTile(                   title: Text('Privacy Policy',                     style: TextStyle(                       fontSize: 17,                       fontWeight: FontWeight.w400,                       letterSpacing: 1.5,                     ),                   ),                   leading: Icon(Icons.privacy_tip, color: Colors.blue,),                   selectedTileColor: Colors.blue,                   onTap: (){                    },                 ),                  ListTile(                   title: Text(                     'LogOut',                     style: TextStyle(                       fontSize: 17,                       fontWeight: FontWeight.w400,                       letterSpacing: 1.5,                     ),                   ),                   leading: Icon(Icons.logout, color: Colors.blue,),                   selectedTileColor: Colors.blue,                   onTap: (){                     Navigator.pushReplacement(context, MaterialPageRoute(                       builder: (context) => LoginPage()                     ));                    },                 ),                  ],             ),           ),         ),         body: Container(),       ),     );   } }  

the data that I am passing to this page is as below -:

I/flutter ( 4512): {address: jaipur, jaipur, alt_number: 9865358577, coach_address: Gautam Budha nagar, noida, coach_id: 2, coach_name: SSG Coaching, coaching_email: SSG@gmail.com, mobile_number: 9999999999, primary_no: 9898557898, res: success, user_id: 3, user_mail: s@gmail.com, user_name: sagar, user_pass: sagar123} 

please help as I am unable to trace the error or find any solution.

        
     
     

Lista de respuestas

1
 
vote
vote
La mejor respuesta
 

Es porque estás usando Navigator.pushReplacement en lugar de navigator.push. Cuando use el control automático, la ruta actual se anula por la nueva ruta.

Entonces usa esto:

  Navigator.push(context, MaterialPageRoute(                       builder: (context) => ProfilePage(                         user_id: userid, user_name:username, mobile_number:mobilenumber, user_address:useraddress,                         user_Email: userEmail,                       )                     ));   

y dentro del profilepage, use

  Navigator.pop(context);   

para volver a la marca de inicio

 

It is because you are using Navigator.pushReplacement instead of Navigator.push. When you use pushReplacement, the current route gets overridden by the new route.

So use this:

Navigator.push(context, MaterialPageRoute(                       builder: (context) => ProfilePage(                         user_id: userid, user_name:username, mobile_number:mobilenumber, user_address:useraddress,                         user_Email: userEmail,                       )                     )); 

And inside the ProfilePage, use

Navigator.pop(context); 

To go back to the homeView

 
 
2
 
vote

Eso es realmente normal porque sus datos no se almacenan en un almacenamiento persistente como SQL Lite, preferencias compartidas, etc. y no debe guardar nada que no sea crucial en el almacenamiento local persistente, ya que es demasiado caro para su tamaño de aplicación. Hay algo más que es una gestión estatal con la gestión del estado, no necesitaría almacenar sus datos en el almacenamiento persistente, en lugar de almacenar sus datos en un estado "semi persistente" temporal. Si desea obtener más información sobre la administración de sus datos sin hacer la actividad de Async, como loca, puede seguir estos pasos a continuación.

Primero es pasar los datos usando Vanilla Navigator Push, y constructor de clase (depende de su tipo de rutas "nombre o no clasificado de rutas") como el @dshukertjr mencionado

  Navigator.push(context, MaterialPageRoute(   builder: (context) => ProfilePage(user_id: userid, user_name:username, mobile_number:mobilenumber, user_address:useraddress,user_Email: userEmail,) ));   

o usando la ruta llamada en su lugar

  Navigator.pushNamed(context, PackageWeight.routeName, arguments: Your data here);   

Aprende aquí sobre las rutas llamadas: https://flutter.dev/docs/cookbook/navigation/named-routes

  • Pros: Esto es simplemente AF simple,
  • Contras: No puede pasar sus datos a las aplicaciones completas con esto solo, ya que esto no es lo suficientemente bueno para administrar el estado durante muchos widgets.

Dos es guardar los datos actuales a nivel local utilizando el proveedor / administración del estado, aprenda aquí sobre la administración del estado. Sugerencia: puede usar el paquete de proveedores, es realmente simple, solo agregue alguna clase de mapa para analizar los datos https://flutter.dev/docs/development/data- y-backend / estado-mgmt / simple

  • Pros: esto es realmente limpio para manejar un estado para muchos widgets.
  • Contras: A veces es excesivo usar proveedor y amplificador; Consumidor para hacer una tarea simple como ahorrar botón Guardar, etc.
  • Asesoramiento personal: Aprende esto, no lo lamentarías, porque puedes usar esto en casi todas partes y AMP; Cada situación en un aleteo para gestionar el estado y los datos (semi persistentemente).
 

that's is really normal because your data isn't stored in persistent storage like SQL lite, shared preferences, etc. And you shouldn't save anything not crucial into persistent local storage, because it's too expensive for your app size. There is something more that is state management with state management you wouldn't require to store your data in persistent storage, instead of store your data in a temporary so-called "semi-persistent" state. if you want to learn more about managing your data without doing async activity like crazy, you can follow these steps below.

first is to pass the data using vanilla Navigator push, and class constructor (depends on your routes type "named or not ClassNamed type of routes") like the one @dshukertjr mentioned

Navigator.push(context, MaterialPageRoute(   builder: (context) => ProfilePage(user_id: userid, user_name:username, mobile_number:mobilenumber, user_address:useraddress,user_Email: userEmail,) )); 

or using named route instead

Navigator.pushNamed(context, PackageWeight.routeName, arguments: Your data here); 

learn here about named routes : https://flutter.dev/docs/cookbook/navigation/named-routes

  • Pros: This is just simple af,
  • cons: you can't passing your data to the entire apps with this only, because this isn't good enough for managing the state for a lot of widgets.

two is to save the current data locally using provider/state management learn here about state management. hint: you can use the provider package, it's really simple just add some map class to parse the data https://flutter.dev/docs/development/data-and-backend/state-mgmt/simple

  • Pros: This is really neat for managing a state for a lot of widgets.
  • Cons: sometimes it's overkill to use provider & consumer to do a simple task like saving button save etc
  • Personal advice: Learn this, you wouldn't regret it, because you can use this almost everywhere & every situation in a flutter to managing state and data (semi persistently).
 
 
   
   

Relacionados problema

0  Flutter - Texto no visible dentro de FlatButton con finca  ( Flutter text not visible inside flatbutton with fittedbox ) 
Estoy aprendiendo aletear y tratar de diseñar una tabla que consiste en celdas con productos planos destinados a realizar alguna operación. Cuando estoy trata...

1  ¿Cómo eliminar el espacio inferior entre la parte inferior de la pantalla y la barra inferior?  ( How to remove bottom space between bottom of the screen and bottom bar ) 
Cómo eliminar el espacio en blanco entre la barra inferior y la parte inferior de la pantalla. También intento aplicar acolchado o margen en contenedor infe...

0  Cuando haga clic en el botón de búsqueda, muestra la pantalla roja con un error sucio  ( When i click on search button it shows red screen with some dirty error ) 
Cuando haga clic en el botón de búsqueda, se muestra "La siguiente afirmación fue lanzada el edificio _searchpage (sucio y dependencias: [_localizationsscope-...

0  TEXTFIELD CAUSANDO PAGESWVIAR PARA ROLLAR ARRIBA  ( Textfield causing pageview to scroll up ) 
Tengo un árbol de widgets bastante convolutados que está causando una vista de página para subir cuando envíe un campo de texto. El efecto: páginaview subi...

0  La vista horizontal de la lista interior de la pila no se desplaza  ( Horizontal list view inside stack is not scrolling ) 
class MenuItem { final String uid; final String category; MenuItem ({ this.uid, this.category }); } class ItemData { final String URL; final S...

0  Flutter Iconos en fila "Right desbordado por X Pixels"  ( Flutter icons in row right overflowed by x pixels ) 
Estoy tratando de construir una barra de pestaña en aleteo anime que se cierre y se abren. Si bien se apertura, porque los iconos dentro de una fila solo son ...

1  ¿Cómo puedo detectar si un widget desbordará sus limitaciones antes de que se presente?  ( How can i detect if a widget will overflow its constraints before it is rendered ) 
Tengo una scp $user@$host:/etc/$file ./$host/conf/ 2>/tmp/Error 1>/dev/null error=$(</tmp/Error) # error catching if [[ -n "$error" ]]; then echo -e "$file ...

1  Flutter Dropdown UI  ( Flutter dropdown ui ) 
Estoy usando el siguiente código, pero no puedo lograr el resultado deseado, soy nuevo en el mundo de Flutter, así que avíseme dónde mejorar para obtener el r...

0  ¿Compartiendo LISTVIALVIO EN Alejado?  ( Sharing listview in flutter ) 
Soy nuevo para aletear. Tengo una lista de desplazamiento para compartir a través de WhatsApp o Mail. Entonces, ¿cómo puedo compartir esta lista como imagen o...

1  Cómo eliminar el espacio adicional en el lado derecho del texto cuando se usa TexToverFlow.Ellipsis  ( How to remove extra space on right side of text when using textoverflow ellipsis ) 
Aquí hay un código: import 'package:flutter/material.dart'; void main() { runApp(MaterialApp(home: Home())); } class Home extends StatelessWidget { @...




© 2022 respuesta.top Reservados todos los derechos. Centro de preguntas y respuestas reservados todos los derechos