简体   繁体   中英

Use pushNamed with Dismissible Widget

I am trying to create a Dismissible widget but I want to have the router history, I mean when I go to another route using the onDismissed event, when user presses back button on that new view be return to the first one.

This is my widget.

Dismissible(
  key: new ValueKey("dismiss_key"),
  direction: DismissDirection.horizontal,
  child: Container(child: this.getTopPlacesSubscription()),
  onDismissed: (direction) {
    if (direction == DismissDirection.endToStart) {
      Navigator.of(context).pushNamed(Router.getRoute(Routes.map));
    }
    if (direction == DismissDirection.startToEnd) {
      Navigator.of(context)
          .pushNamed(Router.getRoute(Routes.camera));
    }
  }

I will appreciate any help. I got an issue trying to do it in this way.

This code block will let you create a random string based on length. Add this to your code.

import 'dart:math';

String _randomString(int length) {
   var rand = new Random();
   var codeUnits = new List.generate(
      length, 
      (index){
         return rand.nextInt(33)+89;
      }
   );

   return new String.fromCharCodes(codeUnits);
}

In your state, define a new variable and give it a random value.

String vk;

@override
void initState() {
  this.vk =  _randomString(10)
}

Then go to your Dismissable widget and replace vk with your string. And here comes the magic part lol. You have to change your vk value in onDismissed . This will pass a new value to Dismissable key, so Flutter will recognize it as a new Widget, which will prevent the error.

Dismissible(
  key: new ValueKey(vk),
  direction: DismissDirection.horizontal,
  child: Container(child: this.getTopPlacesSubscription()),
  onDismissed: (direction) {
    setState(() {
      this.vk = _randomString(10);
    });
    if (direction == DismissDirection.endToStart) {
      Navigator.of(context).pushNamed(Router.getRoute(Routes.map));
    }
    if (direction == DismissDirection.startToEnd) {
      Navigator.of(context)
          .pushNamed(Router.getRoute(Routes.camera));
    }
  }

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