简体   繁体   English

在 Flutter 中滚动页面时无法保存值

[英]Can't save values when I scroll pages in Flutter

I am making a multistep account setup page and ran into an issue, when I scroll to the next page after I have added the data, it erases it on the previous page.我正在制作一个多步骤帐户设置页面并遇到问题,当我在添加数据后滚动到下一页时,它会在上一页中删除它。 In other words, I can't save my data.换句话说,我无法保存我的数据。

I have googled a lot, and know that the solution is in the setting the states and keys, but I am not sure how to implement them in my case.我用谷歌搜索了很多,并且知道解决方案在于设置状态和键,但我不确定如何在我的情况下实现它们。

main.dart main.dart

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:vibe/AllScreens/LoginPage.dart';
import 'package:vibe/AllScreens/MainScreen.dart';
import 'package:vibe/AllScreens/RegistrationScreen.dart';
import 'package:vibe/AllScreens/RessetPassword.dart';
import 'package:vibe/AllScreens/UserInfo.dart';
import 'package:vibe/AllScreens/UserInfo2.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

//may be of every class?
DatabaseReference userRef = FirebaseDatabase.instance.reference().child("users");
//Create second table here for truck drivera data
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        theme: ThemeData(
          //font family can be changed to a ny font
            fontFamily: "Brand Bold",
            primarySwatch: Colors.blue,
            visualDensity: VisualDensity.adaptivePlatformDensity
        ),
        //initialRoute: LoginScreen.idScreen,
        home: UserInfo2(),

        debugShowCheckedModeBanner: false
    );
  }
}

UserInfo2.dart UserInfo2.dart

import 'package:dropdownfield/dropdownfield.dart';
import 'package:flutter/material.dart';

import 'package:vibe/constants.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:vibe/data.dart';


class UserInfo2 extends StatefulWidget {
  static const String idScreen = "userInfo2";
  @override
  _UserInfo2 createState() => _UserInfo2();
}
SwiperController j=SwiperController();
class _UserInfo2 extends State<UserInfo2> {
  // var pages=[];
int tempsex=0;
var pages=[];
@override
   void initState(){
     super.initState();
   pages = [
    [Gender(),1],
    [Gender(),1],
    [Gender(),1],
    [Gender(),1],
    [Gender(),1],
    [Gender(),1],
  ];
  }
  final _key = GlobalKey();
  bool enabled=false;
  @override
  Widget build(BuildContext context) {
    var _onPressed = null;
    if (enabled==true){
      _onPressed = (){
        print("enable");
      };
    }
    return Scaffold(
        backgroundColor: gradientEndColor,
        body: SingleChildScrollView(
          child: Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                  colors: [gradientStartColor, gradientEndColor],
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  stops: [0.3, 0.7]),

            ),

            child: SafeArea(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.all(32.0),
                    child: Column(
                      children: <Widget>[
                        Text(
                          'Let us know a bit more about you!',
                          style: TextStyle(
                            fontFamily: 'Avenir',
                            fontSize: 30,
                            color: const Color(0xffffffff),
                            fontWeight: FontWeight.w900,
                          ),
                          textAlign: TextAlign.left,
                        ),
                      ],
                    ),
                  ),
                  Container(
                    height: 600,

                    padding: const EdgeInsets.only(left: 16),
                    child: Swiper(
                      loop: false,




                      itemCount: 6,//TODO fix this
                      itemWidth: MediaQuery.of(context).size.width-50,
                      itemHeight: 620,
                      layout: SwiperLayout.STACK,

                      //dots
                      pagination: SwiperPagination(
                        builder:
                        DotSwiperPaginationBuilder(activeSize: 20, space: 6),//page swiper

                      ),

                      //height ans stuff can be changed here
                      itemBuilder: (context, index) {
                        return InkWell(

                          child: Stack(//Everythink in box
                            children: <Widget>[
                              Column(
                                children: <Widget>[
                                  Card(


                                    elevation: 16,

                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(16),
                                    ),

                                    color: Colors.white,

                                    child: Padding(
                                      padding: const EdgeInsets.only(top: 16.0, bottom: 16.0),
                                      child: Column(


                                        crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                        children: <Widget>[
                                          pages[index][0],




                                          //SizedBox(height: 40),
                                        ],
                                      ),
                                    ),
                                  ),
                                ],
                              ),

                              //NUMBER INDEX
                              Positioned(
                                right: 10,
                                bottom: 45,
                                child: Text(

                                  pages[index][1].toString(),
                                  style: TextStyle(
                                    fontFamily: 'Avenir',
                                    fontSize: 160,
                                    color: primaryTextColor.withOpacity(0.08),
                                    fontWeight: FontWeight.w900,
                                  ),
                                  textAlign: TextAlign.left,
                                ),
                              ),
                            ],
                          ),
                        );
                      },
                      //control: SwiperControl(),

                    ),
                  ),
                  Column(

                    children: [
                      RaisedButton(
                        color: gradientStartColor,
                        textColor: Colors.white,
                        // focusElevation: 12,

                        child: Container(
                          height: 50.0,

                          //alignment: Alignment.center,
                          child: Center(
                            child: Text(
                              "Finish!",
                              style: TextStyle(fontSize: 18.0, fontFamily: "Brand-Regular"),
                            ),
                          ),
                        ),
                        shape: new RoundedRectangleBorder(
                          borderRadius: new BorderRadius.circular(24),
                        ),
                        onPressed: _onPressed,

                      ),
                    ],
                  )
                ],
              ),
            ),

          ),
        )
    );
  }


}

//===============================================



//===============================================================


class Gender extends StatefulWidget {
  //const Gender({Key key}) : super(key: key);
  //List<int> _selectedItems = List<int>();



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

class _GenderState extends State<Gender> {



  @override
  void initState() {
    _selectedItems.add(gender);
    selected=true;
    print(gender);

  }
  List<String> genders=["Male","Female","Transgender Male", "Transgender Female", "Other"];
  int gender;
  List<int> _selectedItems = List<int>();
  bool selected=false;

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 500,
      child: Container(
        child: Column(
          children: [
            Text(
              "Gender",
              style: TextStyle(
                fontFamily: 'Avenir',
                fontSize: 30,
                color: Colors.black54,
                fontWeight: FontWeight.w900,
              ),
            ),
            SizedBox(height: 8,),
            Text(
              "choose one",
              style: TextStyle(
                fontFamily: 'Avenir',
                fontSize: 20,
                color: Colors.black54,
                fontWeight: FontWeight.normal,
              ),

            ),
            SizedBox(height: 8,),
            SizedBox(
              height: 400,
              child: ListView.builder(


                itemCount: genders.length,
                itemBuilder: (context, index){
                  return
                    Padding(
                      padding: const EdgeInsets.all(4.0),
                      child: Container(
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(16),
                            color: (_selectedItems.contains(index)) ? Colors.greenAccent.withOpacity(0.5) : Colors.transparent,
                            // border: Border.all(color: (_selectedItems.contains(index)) ? gradientStartColor.withOpacity(0.5) : Colors.transparent,),
                            border: Border.all(color: gradientStartColor.withOpacity(0.5) ),
                            boxShadow: [(_selectedItems.contains(index)) ? BoxShadow(
                              color: Colors.grey.withOpacity(0.5),
                              spreadRadius: 2,
                              blurRadius: 7,
                              offset: Offset(0, 3), // changes position of shadow
                            ):BoxShadow(color: Colors.transparent)
                            ]

                        ),
                        child: ListTile(


                            onTap: (){
                              setState(() {
                                if(selected && _selectedItems.contains(index)) {
                                  _selectedItems.removeWhere((val) =>
                                  val == index);
                                  selected = false;
                                  gender=null;

                                }else if(!selected && !_selectedItems.contains(index)){
                                  gender=index;

                                  _selectedItems.add(gender);
                                  selected=true;

                                }
                                else{
                                  _selectedItems.removeWhere((val) =>
                                  val == _selectedItems[0]);
                                  gender=index;
                                  _selectedItems.add(gender);
                                }

                              });
                              print(gender);

                            },
                            title:Text( genders[index].toString(),
                              textAlign: TextAlign.center,)
                        ),
                      ),
                    );
                },
              ),
            ),
          ],
        ),

      ),
    );
  }

}

Widget smth(BuildContext context){
  return Container(
    child: Text(
      "huy"
    ),
  );
}


It is not clear from your provided code, how are you navigating between the pages.从您提供的代码中不清楚,您是如何在页面之间导航的。

In general to save the states of pages while navigating there are following two methods:通常在导航时保存页面状态有以下两种方法:

  1. Indexedstack widget:https://api.flutter.dev/flutter/widgets/IndexedStack-class.html索引堆栈小部件:https://api.flutter.dev/flutter/widgets/IndexedStack-class.html
  2. AutomaticKeepAliveClientMixin: https://api.flutter.dev/flutter/widgets/AutomaticKeepAliveClientMixin-mixin.html AutomaticKeepAliveClientMixin: https://api.flutter.dev/flutter/widgets/AutomaticKeepAliveClientMixin-mixin.html

Pl refer to this prev.请参考此上一页。 question related to bottom navigation and saving the states of pages for more clarity.与底部导航和保存页面状态相关的问题以更清晰。 Same principle applies to what you want to do:同样的原则适用于您想要做的事情:

How to preserve widget states in flutter, when navigating using BottomNavigationBar? 使用 BottomNavigationBar 导航时,如何在 flutter 中保留小部件状态?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM