简体   繁体   中英

Flutter: want to clean data when pressing back button or pressing a button

I want to clean data when i press a button which takes me to next page or backbutton which also clean the data. But when i go back to same page the data is still there and it is not back to init page. Right now, my code look something like this:

import 'package:flutter/material.dart';

DateTime _dateFrom;
DateTime _dateTo;

bool _checked = false;

class ItemDetail extends StatelessWidget{
  var someVariable1 = "something";
  var someVariable2 = "Something elser";
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //Some widgets here
      //_DateTimePickerAndCheckBox is also used here
    );
  }
}

class _DateTimePickerAndCheckBox extends StatefulWidget
{
  @override
  State<StatefulWidget> createState() => _DateTimePickerAndCheckBoxState();
  
}

class _DateTimePickerAndCheckBoxState extends State<_DateTimePickerAndCheckBox>
{
  @override
  Widget build(BuildContext context)
  {
    return Column(); //More widgets here
  }
  
}

All I want is to remove _dateFrom and _dateTo because it is used for stateful widget and later used for stateless widget.

You are declaring variables outside of any classes, so the value you change will also be stored here.

DateTime _dateFrom;
DateTime _dateTo;

class ItemDetail extends StatelessWidget {} ...

Option 1 : You can declare it inside of ItemDetail class.

class ItemDetail extends StatelessWidget {
    DateTime _dateFrom;
    DateTime _dateTo;
}

Option 2

Or if you have several classes in this file which depends on it, create a custom class on its on, and use it. Objects will be created and disposed automatically depending on the screen state.

class _DateTime{
 DateTime from;
 DateTime to;
}

To use it, create a _DateTime object when you want

_DateTime dateTime = _DateTime();
dateTime.from = ... // your code here
dateTime.to = ... // your code here

Remember to pass the object to child widget if you want to use the same object later.

WARNING. You need to have a good understanding on how to pass data between widgets, such as from parents to child, and child to parents.

A good method will be using some state management tool , such as Provider.

Option 3

This is not the proper solution, but just a smart hack, you don't need to change anything in your code, except replacing the close button method with:

onPressed/ontap : () {
 _dateFrom = null;
 _dateTo = null;
 Navigator.of(context).pop();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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