-2

Estou estudando Flutter e aprendendo a consumir API, e com isso estou fazendo um app basico com api de uma pokedex, mas estou tendo erros, consigo consumir a api, porem não consigo usar o setState ou se uso o setState não consigo chamar o metodo da api

segue codigo abaixo:

import 'package:flutter/material.dart';
import 'package:testepoke/poke_info.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  TextEditingController valor = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Pokédex', style: TextStyle(color: Colors.white,
            fontWeight: FontWeight.w500)),
        backgroundColor: Colors.red,
      ),
      body: Center(
        child: Column(mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Digite o nome do seu Pokemon',
              style: TextStyle(fontSize: 22,
              ),),
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 40, horizontal: 60),
              child: TextField(
                controller: valor,
                decoration: InputDecoration(
                    labelStyle: TextStyle(color: Colors.red),
                    hintText: 'Nome do Pokemon',
                    hintStyle: TextStyle(color: Colors.grey),
                    border: OutlineInputBorder(
                    )
                ),
              ),
            ),
            ElevatedButton(
              style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.red,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(13)
                  )
              ),
              onPressed: () {
                setState(() {
                  api(valor.text);
                  Navigator.push(context, MaterialPageRoute(
                      builder: (context) => PokeInfo()
                  ));
                });
              }, child: Text('Pesquisar',
              style: TextStyle(color: Colors.white, fontSize: 17),),
            )
          ],
        ),
      ),
    );
  }
}

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:testepoke/requerimets.dart';


class PokeInfo extends StatefulWidget {

  @override
  State<PokeInfo> createState() => _PokeInfoState();
}

class _PokeInfoState extends State<PokeInfo> {

  String resultado = '';

  api(String testeapi) async {
    var url = 'https://pokeapi.co/api/v2/pokemon/$testeapi';
    var response = await http.get(Uri.parse(url));
    var json = jsonDecode(response.body);
    var data = Data.fromJson(json);
    setState(() {
      resultado = "${data.name}";
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(backgroundColor: Colors.red,
      title: Text('N°      Name',style: TextStyle(
        color: Colors.white, fontSize: 20
      ),),),
      body: Column(
        children: [
          Text(resultado),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 100),
            child: Image.network('https://assets.pokemon.com/assets/cms2/img/pokedex/full/025.png'),
          )
        ],
      ),
    );
  }
}

1
  • Fala Lucas, Bem vindo ao site. Que estranho, você chama o método api(valor.text) na primeira tela, mas só vi ele definido na segunda tela. Acho que você deve estar se confundindo sobre a ordem que as coisas acontecem. Poderia editar sua pergunta e colocar exatamente qual comportamento você deseja, e qual o erro que está dando? Acredito que isso irá aumentar as chances de obter uma resposta. Um abraço e boa sorte!
    – Naslausky
    16/11/2022 às 22:49

1 Resposta 1

0

Acredito que fique melhor se você passar o nome do pokemon como parâmetro e fazer a requisição no initState.

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:testepoke/requerimets.dart';


class PokeInfo extends StatefulWidget {
  final String nomePokemon;

  const PokeInfo({
    super.key,
    required this.nomePokemon,
  });

  @override
  State<PokeInfo> createState() => _PokeInfoState();
}

class _PokeInfoState extends State<PokeInfo> {

  String resultado = '';

  api(String testeapi) async {
    var url = 'https://pokeapi.co/api/v2/pokemon/$testeapi';
    var response = await http.get(Uri.parse(url));
    var json = jsonDecode(response.body);
    var data = Data.fromJson(json);
    setState(() {
      resultado = "${data.name}";
    });
  }

  @override
  void initState() {
     super.initState();
     api(widget.nomePokemon);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(backgroundColor: Colors.red,
      title: Text('N°      Name',style: TextStyle(
        color: Colors.white, fontSize: 20
      ),),),
      body: Column(
        children: [
          Text(resultado),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 100),
            child: Image.network('https://assets.pokemon.com/assets/cms2/img/pokedex/full/025.png'),
          )
        ],
      ),
    );
  }
}
import 'package:flutter/material.dart';
import 'package:testepoke/poke_info.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  TextEditingController valor = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Pokédex', style: TextStyle(color: Colors.white,
            fontWeight: FontWeight.w500)),
        backgroundColor: Colors.red,
      ),
      body: Center(
        child: Column(mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Digite o nome do seu Pokemon',
              style: TextStyle(fontSize: 22,
              ),),
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 40, horizontal: 60),
              child: TextField(
                controller: valor,
                decoration: InputDecoration(
                    labelStyle: TextStyle(color: Colors.red),
                    hintText: 'Nome do Pokemon',
                    hintStyle: TextStyle(color: Colors.grey),
                    border: OutlineInputBorder(
                    )
                ),
              ),
            ),
            ElevatedButton(
              style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.red,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(13)
                  )
              ),
              onPressed: () {
                setState(() {
    
                  Navigator.push(context, MaterialPageRoute(
                      builder: (context) => PokeInfo(nomePokemon: valor.text)
                  ));
                });
              }, child: Text('Pesquisar',
              style: TextStyle(color: Colors.white, fontSize: 17),),
            )
          ],
        ),
      ),
    );
  }
}

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .