Как использовать GetX Navigation от страницы к самой себе

У меня есть такой список:

  List<Country> countries = [
    Country(name: 'United States', border: ['Mexico', 'Canada']),
    Country(name: 'Mexico', border: ['United States']),
    Country(name: 'Canada'),
  ];

На странице HomeView будет список countries.name, при нажатии = ›перейдите на страницу DetailsView, на которой отображается countries.border

На этой странице DetailsView я хочу, чтобы при нажатии на какой countries.border он переместился на новую страницу Detailsview, которая countries.name == countries.border.

введите описание изображения здесь

Мне удалось это сделать с Navigator().push

 //Use Navigator().push
                          Navigator.of(context).push(MaterialPageRoute(
                            builder: (_) => DetailView(country: controller.countries[i]),

но не могу этого сделать с Get.to:

//Use Get.to not succeed
                          Get.to(() => DetailView(country: controller.countries[i]));

так что, пожалуйста, помогите мне, это полный код:

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

void main() async {
  runApp(GetMaterialApp(
    debugShowCheckedModeBanner: false,
    home: HomeView(),
  ));
}

class Country {
  String name;
  List<String> border;

  Country({this.name, this.border});
}

class HomeController extends GetxController {
  List<Country> countries = [
    Country(name: 'United States', border: ['Mexico', 'Canada']),
    Country(name: 'Mexico', border: ['United States']),
    Country(name: 'Canada'),
  ];
}

class HomeView extends GetView<HomeController> {
  final controller = Get.put(HomeController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('List Countries')),
      body: ListView.separated(
        separatorBuilder: (_, __) => Divider(),
        itemCount: controller.countries.length,
        itemBuilder: (BuildContext context, int index) {
          return ListTile(
            title: Text(controller.countries[index].name),
            onTap: () => Get.to(
              () => DetailView(
                country: controller.countries[index],
              ),
            ),
          );
        },
      ),
    );
  }
}

class DetailView extends GetView<HomeController> {
  final Country country;

  DetailView({this.country});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(country.name)),
      body: Column(
        children: [
          Text('Border'),
          if (country.border != null)
            Expanded(
              child: ListView.builder(
                itemCount: country.border.length,
                itemBuilder: (BuildContext context, int index) {
                  return Column(
                    children: [
                      GestureDetector(
                        onTap: () {
                          final currentCountry = controller.countries.firstWhere(
                              (e) => e.name == country.border[index],
                              orElse: () => null);
                          int i = controller.countries.indexOf(currentCountry);

                          //Use Get.to not succeed
                          // Get.to(() => DetailView(country: controller.countries[i]));

                          //Use Navigator().push
                          Navigator.of(context).push(MaterialPageRoute(
                            builder: (_) => DetailView(country: controller.countries[i]),
                          ));
                        },
                        child: Text(
                          country.border[index],
                          style:
                              TextStyle(color: Colors.blue, decoration: TextDecoration.underline),
                        ),
                      )
                    ],
                  );
                },
              ),
            ),
        ],
      ),
    );
  }
}



person Kel    schedule 03.06.2021    source источник


Ответы (1)


Вы можете добавить флаг preventDuplicates:

 Get.to(() => DetailView(country: controller.countries[i]), preventDuplicates: false);

Итак, я думаю, вам нужно будет поместить контроллер с помощью Create в основной файл, поэтому каждый раз, когда вы вызываете экран, он будет создавать для этого еще один контроллер:

//main.dart
Get.create(() => Controller());

//so you call this way on the DetailView page
final controller = Get.find();
person Jorge Vieira    schedule 03.06.2021