flutter - ¿Por qué onTap y sus funciones no funcionan en InkWell?

CorePress2024-01-24  9

Estoy intentando abrir el enlace cuando lo toco en ListWheelScrollView, pero no funciona. Ni siquiera entra al OnTap

import 'package:flutter/material.dart';
import 'package:string_validator/string_validator.dart';
import 'package:url_launcher/url_launcher.dart';

class News extends StatefulWidget {
  final Map news;

  @override
  _NewsState createState() => _NewsState();

  const News({Key key, this.news}) : super(key: key);
}

class _NewsState extends State<News> {
  Map test;
  double textPadding = 290;

  // ignore: non_constant_identifier_names
  @override
  void initState() {
    super.initState();
  }

  launchURL(String url) async {
    if (await canLaunch(url)) {
      await launch(url, forceWebView: true);
    } else {
      throw 'Could not launch $url';
    }
  }

  @override
  Widget build(BuildContext context) {
    test = (ModalRoute.of(context).settings.arguments);
    var fixedTest = test['data'].news4today;

    checkUrls() {
      for (int i = 0; i < fixedTest.length; i++) {
        if (fixedTest[i]['urlToImage'] == null ||
            !isURL(fixedTest[i]['urlToImage'])) {
          fixedTest[i]['urlToImage'] =
              'https://i.pinimg.com/originals/8a/eb/d8/8aebd875fbddd22bf3971c3a7159bdc7.png';
        }
        if (fixedTest[i]['url'] == null || !isURL(fixedTest[i]['url'])) {
          fixedTest[i]['url'] = 'https://google.com';
        }
      }
    }

    checkUrls();

    return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          title: Center(child: Text('News')),
          backgroundColor: Colors.deepPurpleAccent,
        ),
        body: ListWheelScrollView.useDelegate(
            itemExtent: 400,
            diameterRatio: 9,
            squeeze: 1.2,
            physics: BouncingScrollPhysics(),
            onSelectedItemChanged: (index) {
              // debugPrint(index.toString());
            },
            childDelegate: ListWheelChildBuilderDelegate(
                childCount: 100,
                builder: (context, index) => Container(
                      child: Stack(
                        alignment: Alignment.topCenter,
                        children: <Widget>[
                          Material(
                            child: InkWell(
                              onDoubleTap: () {
                                launchURL(fixedTest[index]['urlToImage']);
                              },
                              child: Container(
                                height: 353.0,
                                decoration: BoxDecoration(
                                  image: DecorationImage(
                                      fit: BoxFit.scaleDown,
                                      alignment: FractionalOffset.center,
                                      image: NetworkImage(
                                          fixedTest[index]['urlToImage'])),
                                ),
                              ),
                            ),
                          ),
                          Container(
                            margin: EdgeInsets.only(top: 285),
                            child: Padding(
                              padding: const EdgeInsets.all(10),
                              child: SizedBox(
                                  child: Text(
                                fixedTest[index]['title'],
                                style: TextStyle(fontSize: 16),
                                maxLines: 4,
                                textAlign: TextAlign.center,
                              )),
                            ),
                            decoration: BoxDecoration(
                              color: Colors.purple[100],
                              boxShadow: [
                                BoxShadow(
                                  color: Colors.grey.withOpacity(0.8),
                                  spreadRadius: 1,
                                  blurRadius: 3,
                                  offset: Offset(1, 1),
                                ),
                              ],
                            ),
                          )
                        ],
                      ),
                    ))));
  }
}

Estaba intentando eliminar contenedores con tinta, pero si lo hago, arruinará la aplicación debido al margen de texto. Probé también con DoubleTap.



------------------------------------

En lugar de utilizar el tintero, deberías utilizar el widget RichText para obtener texto que se pueda tocar. A continuación se muestra el código para el mismo. Usar texto normal y tintero no es una buena práctica, especialmente porque si desea agregar un texto normal y un enlace inmediatamente después tendrá que usar el widget Fila y si el enlace va a la siguiente línea, no aparecerá.bien como se esperaba.

import 'package:flutter/gestures.dart';


new RichText(
      text: new TextSpan(text: 'Non touchable. ', children: [
        new TextSpan(
          text: 'Tap here.',
          recognizer: new TapGestureRecognizer()..onTap = () => print('Tap Here onTap'),
        )
      ]),
    );

Acerca de su error, en lugar de su función launchURL, intente imprimir algo para saber si se reconoce o no el gesto de doble toque. Si obtienes la declaración impresa al tocar dos veces, entonces es un error en tu función launchURL.

4

Tengo un problema, no se imprime Toque aquí... en absoluto cuando hago clic en él.

- Mike

26/03/2021 a las 20:58

Ok, espera, probaré tu código y volveré contigo

- Sarvesh Dalvi

26/03/2021 a las 20:59

Acabo de comprobarlo y hay un problema con el widget proporcionado por Flutter. Puede intentar utilizar este paquete como solución alternativa: pub.dev/packages/clickable_list_wheel_view

- Sarvesh Dalvi

26/03/2021 a las 21:18

Está bien, lo intentaré más tarde. ¡Gracias!

- Mike

26/03/2021 a las 21:24



------------------------------------

InkWell debe tener material padre. Envuelva su widget InkWell en Material. Consulte la documentación de InkWell. Además, si launchURL(fixedTest[index]['url']) es una función asíncrona, debe esperar a que esta función detenga su aplicación hasta que se complete.

7

Intenté envolverlo con Material(), pero aún no hay respuesta

- Mike

26/03/2021 a las 20:09

¿Se puede agregar al código de función de respuesta? ¿O eliminarlo y probar la impresión sin él?

-Simón Sot

26/03/2021 a las 20:11

Actualizado. Lo siento si el código huele mal, solo estoy estudiando.

- Mike

26/03/2021 a las 20:18

No te preocupes, intenta usarlo con await añadido como en el código siguiente

-Simón Sot

26/03/2021 a las 20:24

No puedo entender cómo debo usar await allí. Dice "La expresión de espera sólo se puede utilizar en una función asíncrona". ", porque a cambio es Scaffold()

- Mike

26 de marzo de 2021 a las 20:29

Su guía para un futuro mejor - libreflare
Su guía para un futuro mejor - libreflare