如何返回具有参数的屏幕?

时间:2019-08-17 16:39:53

标签: flutter dart

我有三个屏幕。一个没有参数,第二个有两个参数。当我转到第三个屏幕并按Android的后退按钮时,返回到第一个屏幕,而不是第二个屏幕。

我尝试使用WillPopScope操纵后退按钮,但是没有用。我认为问题是由于秒的参数引起的。

这是第三个(ChosenOption)和第二个(Options2)屏幕:


import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:cruke_app/ui/options2.dart';
import 'package:flutter/material.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:rating_bar/rating_bar.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:cruke_app/ui/map.dart';
import 'package:flutter/services.dart' show rootBundle;

class ChosenOption extends StatefulWidget {
  final String option;
  final DocumentSnapshot document;

  ChosenOption({Key key, @required this.document, this.option}) : super(key: key);

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

class _ChosenOptionState extends State<ChosenOption> {
  Completer<GoogleMapController> _controller = Completer();
  GoogleMapController mapController;
  String _mapStyle;
  static const LatLng _center = const LatLng(45.521563, -122.677433);

  @override
  void initState() {
    super.initState();

    rootBundle.loadString('assets/map_style.txt').then((string) {
      _mapStyle = string;
    });
  }

  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
    mapController.setMapStyle(_mapStyle);
    _controller.complete(controller);
  }

  @override
  Widget build(BuildContext context) {
    double _rating = 0;

    return Scaffold(
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Stack(
              children: <Widget>[
                CarouselSlider(
                  height: 200.0,
                  items: [1,2,3,4,5].map((i) {
                    return Builder(
                      builder: (BuildContext context) {
                        return Container(
                          width: MediaQuery.of(context).size.width,
                          margin: EdgeInsets.symmetric(horizontal: 1.0),
                          decoration: BoxDecoration(
                            image: DecorationImage(
                              image: NetworkImage(widget.document["image"]),
                              fit: BoxFit.cover,
                            ),
                          ),
                          child: Text('$i', style: TextStyle(fontSize: 16.0),)
                        );
                      },
                    );
                  }).toList(),
                ),
              ],
            ),
            Container(
              margin: EdgeInsets.only(top: 20.0, left: 13.0), 
              child: Row(
                children: <Widget>[
                  Container(
                    width: MediaQuery.of(context).size.width * 0.8,
                    child: Text(widget.document["title"], 
                    style: TextStyle(color: Colors.black, 
                    fontSize: 20.0, fontWeight: FontWeight.bold),),
                  ),
                  Container(
                    width: MediaQuery.of(context).size.width * 0.15,
                    child: RawMaterialButton(
                      onPressed: () {},
                      child: Icon(
                        Icons.favorite,
                        color: Colors.white,
                        size: 20.0,
                      ),
                      shape: CircleBorder(),
                      elevation: 2.0,
                      fillColor: Colors.red,
                      padding: EdgeInsets.all(8.0),
                    ),
                  ),
                ],
              ),
            ),
            Row(
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(left: 13.0),
                  child: Icon(Icons.star, size: 18.0, color: Colors.black),
                ),
                Container(
                  margin: EdgeInsets.only(left: 5.0),
                  child: RatingBar(
                    onRatingChanged: (rating) => setState(() => widget.document["rating"] == rating),
                    filledIcon: Icons.star,
                    emptyIcon: Icons.star_border,
                    halfFilledIcon: Icons.star_half,
                    isHalfAllowed: true,
                    filledColor: Colors.yellow,
                    emptyColor: Colors.grey,
                    halfFilledColor: Colors.yellow, 
                    size: 18,
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(left: 5.0),
                  child: Text(widget.document["avaliations"].toString()+"   |  ", style: TextStyle(color: Colors.black, fontSize: 10.0),),
                ),

                Text(widget.document["city"], style: TextStyle(color: Colors.black, fontSize: 10.0),), 
              ],
            ),
            Container(
              margin: EdgeInsets.all(13.0),
              child: Text(widget.document["text"]),
            ),
            Divider(),
            Text("Avaliações", style: TextStyle(fontSize: 20,),),
            buildEvaluation(_rating, "images/restaurant.jpg", "Leandro", "Minas Gerais - MG", "6 dias atrás"),
            buildEvaluation(_rating, "images/restaurant.jpg", "Leandro", "Minas Gerais - MG", "10 dias atrás"),
            buildEvaluation(_rating, "images/restaurant.jpg", "Leandro", "MInas Gerais - MG", "16 dias atrás"),
            Stack(
              children: <Widget>[
                Column(
                  children: <Widget>[
                    Container(
                      margin: EdgeInsets.only(top: 20.0),
                      child: Text("Avaliar este Restaurante", style: TextStyle(fontSize: 18),),
                    ),
                    Container(
                      alignment: Alignment.center,
                      margin: EdgeInsets.only(top: 10.0),
                      child: RatingBar(
                        onRatingChanged: (rating) => setState(() => _rating = rating),
                        filledIcon: Icons.star,
                        emptyIcon: Icons.star_border,
                        halfFilledIcon: Icons.star_half,
                        isHalfAllowed: true,
                        filledColor: Colors.yellow,
                        emptyColor: Colors.black,
                        halfFilledColor: Colors.yellow, 
                        size: 20,
                      ),
                    ),
                    Container(
                      width: 300.0,
                      margin: EdgeInsets.only(bottom: 50.0),
                      child: TextField(
                        decoration: InputDecoration(
                          suffixIcon: Padding(
                            padding: EdgeInsetsDirectional.only(end: 12.0),
                            child: Icon(Icons.send, color: Colors.black),
                          ),
                          hintText: "Comentar...",
                          hintStyle: TextStyle(color: Colors.grey, fontSize: 15.0),
                          fillColor: Colors.white,
                        ),
                        textAlign: TextAlign.end,
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(right: 220.0, bottom: 5.0),
                      child: Text("Local no mapa",
                        style: TextStyle(fontWeight: FontWeight.bold, color: Colors.black),
                      ),
                    ),
                    Container(
                      width: 340.0,
                      height: 200.0,
                      margin: EdgeInsets.only(bottom: 10.0),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        boxShadow: <BoxShadow>[
                          BoxShadow(
                            color: Colors.grey,
                            offset: Offset(1.0, 1.0),
                            blurRadius: 10.0,
                          ),
                        ],
                        borderRadius: BorderRadius.circular(10.0),
                      ), 
                      child: GoogleMap(
                        mapType: MapType.normal,
                        onMapCreated: _onMapCreated,
                        initialCameraPosition: CameraPosition(
                          target: _center,
                          zoom: 18.0,
                        ),
                      ),
                    ), 
                    RaisedButton.icon(   
                      onPressed: (){
                        Navigator.push(
                          context,
                          MaterialPageRoute(builder: (context) => CrukeMap()),
                        );
                      },
                      label: Text(
                        'TRAÇAR ROTA',
                        style: TextStyle(fontSize: 13, color: Colors.white, fontWeight: FontWeight.bold),               
                      ),
                      color: Colors.red,
                      icon: Icon(Icons.directions, color: Colors.white),
                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30.0)),
                    ),
                    Row(
                      children: <Widget>[
                        Container(
                          margin: EdgeInsets.only(left: 20.0, top: 40.0),
                          child: Icon(Icons.place, color: Colors.red, size: 18,),
                        ),
                        Container(
                          margin: EdgeInsets.only(left: 10.0, top: 40.0),
                          child: Text("R. Sete de Setembro, Porto Seguro - BA, 45810-000", style: TextStyle(fontSize: 12.0),),
                        ),
                      ],  
                    ),
                    Row(
                      children: <Widget>[
                        Container(
                          margin: EdgeInsets.only(left: 20.0, top: 10.0),
                          child: Icon(Icons.local_phone, color: Colors.red, size: 18,),
                        ),
                        Container(
                          margin: EdgeInsets.only(left: 10.0, top: 10.0),
                          child: Text("(73)99906-3724", style: TextStyle(fontSize: 12.0),),
                        ),
                      ],  
                    ),
                    Row(
                      children: <Widget>[
                        Container(
                          margin: EdgeInsets.only(left: 20.0, top: 10.0, bottom: 50.0),
                          child: Icon(Icons.timer, color: Colors.red, size: 18,),
                        ),
                        Container(
                          margin: EdgeInsets.only(left: 10.0, top: 10.0, bottom: 50.0),
                          child: Text("Horário de Funcionamento: 12:00 às 20:00", style: TextStyle(fontSize: 12.0),),
                        ),
                      ],  
                    ),
                  ],
                ),   
              ],
            ),
          ], 
        ),
      ),
    );
  }

  Widget buildEvaluation(double _rating, String image, String name, String location, String time){
    return Stack(
      children: <Widget>[
        Positioned(
          child: Row(
            children: <Widget>[
              Padding(
                padding: EdgeInsets.only(left: 20.0, right: 20.0, top: 30.0),
                child: Container(
                  height: 80.0,
                  width: 80.0,
                  decoration: BoxDecoration(
                    color: Colors.blue,
                    shape: BoxShape.circle,
                    image: DecorationImage(
                      fit: BoxFit.fill,
                      image: ExactAssetImage(image),
                    ),
                )),
              ),
              Container(
                margin: EdgeInsets.only(left: 20.0),
                child: RatingBar(
                  onRatingChanged: (rating) => setState(() => _rating = rating),
                  filledIcon: Icons.star,
                  emptyIcon: Icons.star_border,
                  halfFilledIcon: Icons.star_half,
                  isHalfAllowed: true,
                  filledColor: Colors.yellow,
                  emptyColor: Colors.grey,
                  halfFilledColor: Colors.yellow, 
                  size: 20,
                ),
              ),
              Container(
                margin: EdgeInsets.only(left: 10.0),
                child: Text(time, style: TextStyle(color: Colors.black, fontSize: 10.0),),
              ),
            ],
          ),
        ),
        Column(
          children: <Widget>[
            Container(
              padding: EdgeInsets.only(top: 110.0, left: 5.0),
              child: Text(name),
            ),
            Container(
              padding: EdgeInsets.only(top: 5.0, left: 10.0),
              child: Text(location),
            ),
          ],
        ),
        Container(
          margin: EdgeInsets.only(left: 140.0, top: 70.0, bottom: 10.0),
          width: 200.0,
          child: Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt" +
          "ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." ), 
        ),
      ],
    );
  }
}

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:cruke_app/main.dart';
import 'package:flutter/material.dart';
import 'package:rating_bar/rating_bar.dart';
//import 'package:cruke_app/main.dart';
import 'package:cruke_app/ui/chosen_option.dart';

class Options2 extends StatefulWidget {

final String text, city;

  Options2({Key key, @required this.text, this.city}) : super(key: key);
  @override
  _Options2State createState() => _Options2State();
}

class _Options2State extends State<Options2> {

  @override
  Widget build(BuildContext context) {
    TextEditingController controller = new TextEditingController();

    return MaterialApp(
      home: Scaffold(
        body: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Container(
                alignment: Alignment.center,
                padding: EdgeInsets.only(left: 20.0, right: 20.0),
                width: 500,
                height: 150,
                child: Container(
                  decoration: BoxDecoration(
                    boxShadow: <BoxShadow>[
                      BoxShadow(
                        color: Colors.grey,
                        offset: Offset(1.0, 1.0),
                        blurRadius: 5.0,
                      ),
                    ],
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(30.0),
                  ),
                  child: Padding(
                    padding: EdgeInsets.all(10.0),
                    child: TextField(
                      controller: controller,
                      decoration: InputDecoration(
                        suffixIcon: Padding(
                          padding: EdgeInsetsDirectional.only(end: 12.0),
                          child: Icon(Icons.search),
                        ), 
                        hintText: "Porto Seguro - BA",
                        hintStyle: TextStyle(color: Colors.grey, fontSize: 15.0),
                        fillColor: Colors.grey,
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(28.0),
                          borderSide: BorderSide(
                            width: 5.0,
                            color: Colors.grey,
                          ),
                        ),     
                      ),
                    ),
                  ),
                ),
              ),
              Text("CATEGORIAS", style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold)),

              Container(
                padding: EdgeInsets.only(top: 8.0),
                child: Row(
                  children: <Widget>[
                    Expanded(
                      child: RawMaterialButton(
                        onPressed: () {
                          if(controller.text != null){
                            if(testData("tours", controller.text)){
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => Options2(text: "tours", city: controller.text),
                                ),
                              );
                            }
                          }

                        },
                        child: Icon(
                          Icons.restaurant,
                          color: Colors.white,
                          size: 30.0,
                        ),
                        shape: CircleBorder(),
                        elevation: 2.0,
                        fillColor: Colors.red,
                        padding: EdgeInsets.all(8.0),
                      ),
                    ),

                    Expanded(
                      child: RawMaterialButton(
                        onPressed: () {
                          if(controller.text != null){
                            if(testData("restaurant", controller.text)){
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => Options2(text: "restaurant", city: controller.text),
                                ),
                              );
                            }
                          }
                        },
                        child: Icon(
                          Icons.restaurant,
                          color: Colors.white,
                          size: 30.0,
                        ),
                        shape: CircleBorder(),
                        elevation: 2.0,
                        fillColor: Colors.red,
                        padding: EdgeInsets.all(8.0),
                      ),
                    ),

                    Expanded(
                      child: RawMaterialButton(
                        onPressed: () {
                          if(controller.text != null){
                            if(testData("amusement", controller.text)){
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => Options2(text: "amusement", city: controller.text),
                                ),
                              );
                            }
                          }
                        },
                        child: Icon(
                          Icons.restaurant,
                          color: Colors.white,
                          size: 30.0,
                        ),
                        shape: CircleBorder(),
                        elevation: 2.0,
                        fillColor: Colors.red,
                        padding: EdgeInsets.all(8.0),
                      ),
                    ),
                    Expanded(
                      child: RawMaterialButton(
                        onPressed: () {
                          if(controller.text != null){
                            if(testData("tourism", controller.text)){
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => Options2(text: "tourism", city: controller.text),
                                ),
                              );
                            }
                          }
                        },
                        child: Icon(
                          Icons.restaurant,
                          color: Colors.white,
                          size: 30.0,
                        ),
                        shape: CircleBorder(),
                        elevation: 2.0,
                        fillColor: Colors.red,
                        padding: EdgeInsets.all(8.0),
                      ),
                    ),
                  ],
                ),
              ),
              Row(
                children: <Widget>[
                  Expanded(
                    child: Padding(
                      padding: EdgeInsets.only(left: 18.0),
                      child: Text("Passeios"),
                    ),
                  ),
                  Expanded(
                    child: Padding(
                      padding: EdgeInsets.only(left: 3.0),
                      child: Text("Restaurantes"),
                    ),

                  ),
                  Expanded(
                    child: Padding(
                      padding: EdgeInsets.only(left: 14.0),
                      child: Text("Diversões"),
                    ),  
                  ),
                  Expanded(
                    child: Padding(
                      padding: EdgeInsets.only(left: 18.0),
                      child: Text("Turismo"),
                    ),
                  ),
                ],
              ),
              Container(
                padding: EdgeInsets.all(10.0),
                width: double.infinity,
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                    boxShadow: <BoxShadow>[
                      BoxShadow(
                        color: Colors.grey,
                        offset: Offset(1.0, 1.0),
                        blurRadius: 10.0,
                      ),
                    ],
                    borderRadius: BorderRadius.circular(10.0),
                  ), 
                  child: Column(
                    children: <Widget>[
                      Container(
                        padding: EdgeInsets.all(15.0),
                        child: Text("Sugestões", style: TextStyle(color: Colors.black)),
                      ),
                      Container(
                        child: FutureBuilder<QuerySnapshot>(
                          future: Firestore.instance.collection(widget.text).where("city", isEqualTo: widget.city).getDocuments(),
                          builder: (context, snapshot){
                            if(!snapshot.hasData){
                              return Center(child: CircularProgressIndicator());
                            }else{
                              return snapshot.data.documents.isEmpty ? Center(child: Text("Sua busca não foi encontrada!")) : ListView.builder(
                                physics: const NeverScrollableScrollPhysics(),
                                scrollDirection: Axis.vertical,
                                shrinkWrap: true,
                                itemCount: snapshot.data.documents.length,
                                itemBuilder: (context, index){
                                  return buildCard(context, snapshot.data.documents[index], widget.text);
                                },
                              );
                            }
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ),

            ],
          ),

        ),
      ),
    );
  }

  bool testData(String collection, String city){
    try{
      var data = Firestore.instance.collection(collection).where("city", isEqualTo: city).snapshots();
      if(data != null){
        return true;
      }
    }catch(error){
      return false;
    }
  }

  Widget buildCard(BuildContext context, DocumentSnapshot document, String collection){
    return Material(
      child: InkWell(
        onTap: (){
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => ChosenOption(document: document, option: collection),
            ),
          );
        },
        child: Container(
          padding: EdgeInsets.only(top: 127.0),
          margin: EdgeInsets.only(right: 10.0, left: 10.0, bottom: 15.0),
          decoration: BoxDecoration(
            image: DecorationImage(
              image: NetworkImage(document['image']),
              fit: BoxFit.cover,
            ),
            borderRadius: BorderRadius.circular(10.0),
          ),
          width: double.infinity,
          height: 200.0,
          child: Column(
            children: <Widget>[
              Container(
                alignment: Alignment.topLeft,
                padding: EdgeInsets.only(left: 5.0),
                child: Text(document['title'], 
                  style: TextStyle(
                    fontSize: 16.0, 
                    fontWeight: FontWeight.bold, 
                    color: Colors.white,
                  ),
                ),
              ),
              Row(
                children: <Widget>[
                  Container(
                    padding: EdgeInsets.only(left: 5.0),
                    child: Icon(Icons.star, size: 18.0, color: Colors.white),
                  ),
                  Container(
                    padding: EdgeInsets.only(left: 5.0, right: 5.0),
                    child: RatingBar(
                      onRatingChanged: (rating) => setState(() => rating = document['rating']),
                      filledIcon: Icons.star,
                      emptyIcon: Icons.star_border,
                      halfFilledIcon: Icons.star_half,
                      isHalfAllowed: true,
                      filledColor: Colors.yellow,
                      emptyColor: Colors.grey,
                      halfFilledColor: Colors.yellow, 
                      size: 18,
                    ),
                  ),

                  Container(
                    child: Text(document['avaliations'].toString(), style: TextStyle(color: Colors.white, fontSize: 9.0),),
                  ),
                  Container(
                    child: Text("  |  " + document['city'], style: TextStyle(color: Colors.white, fontSize: 9.0),),
                  ),
                ],
              ),
              Container(
                height: 36.0,
                width: double.infinity,
                decoration: BoxDecoration(
                  color: Colors.white,
                  boxShadow: <BoxShadow>[
                    BoxShadow(
                      color: Colors.grey,
                      offset: Offset(1.0, 1.0),
                      blurRadius: 10.0,
                    ),
                  ],
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.zero, topRight: Radius.zero,
                    bottomLeft: Radius.circular(10.0), bottomRight: Radius.circular(10.0)),
                ),
                child: Padding(
                  padding: EdgeInsets.all(5.0),
                  child: Text(document['text'],
                    style: TextStyle(fontSize: 10.0),),
                ),
              ),

            ],
          ),
        ),
      ),
    );

  }
}

1 个答案:

答案 0 :(得分:0)

请使用包back_button_interceptor https://pub.dev/packages/back_button_interceptor

在简单的情况下,当您需要拦截Android后退按钮时,通常会将WillPopScope添加到小部件树中。但是,在开发与后退按钮交互的有状态小部件时,使用BackButtonInterceptor更加方便

用法示例

@override
void initState() {
   super.initState();
   BackButtonInterceptor.add(myInterceptor);
}

@override
void dispose() {
   BackButtonInterceptor.remove(myInterceptor);
   super.dispose();
}

bool myInterceptor(bool stopDefaultButtonEvent) {
   print("BACK BUTTON!"); // Do some stuff.
   return true;
}

类似问题How to deactivate or override the Android "BACK" button, in Flutter?