Error when connecting API to Flutter (Dio)

Asked

Viewed 294 times

0

Good afternoon!

I’m trying to learn how to use the Dio to integrate an API that I am also developing and for this I tried to carry out a simple test.

I simply tried to make a print on the terminal even using this code snippet:

class _MyHomePageState extends State<MyHomePage> {
  
  void teste() async {
    Response res;
    Dio dio = new Dio();
    res = await dio.get("192.168.15.10:3000/welcome");
    print(res.data.toString());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Verifique o teste no terminal!!!:',
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: teste,
        child: Icon(Icons.adjust),
      ), 
    );
  }
}

The route (Express) I’m using on Dio.get():

router.get('/', (req, res) => {
    res.send({ message: 'Parabéns você está conectado a API' })
})

But when I run test in the app by pressing the button, I get the following error (As it is too big, I decided to upload a screenshot of it, aiming not to pollute the post too much):

https://ibb.co/8mY1xq5

What did I do wrong? Thanks in advance.

  • I never used this Dio, I already accessed the API in Flutter using a dependency called http, I always use res.body. Try trading the res.data for the res..

  • Another thing, I think you should use a widget called Futurebuilder to work with asynchronous functions. I’m gonna put some codes in here that I made that might help you

1 answer

1

VIEW

return Scaffold(
      appBar: AppBar(
        title: Text('Users'),
      ),
      body: Container(
        child: FutureBuilder<List<User>>(
            future: _placeHolderService.getUsers(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return ListView.builder(
                  itemCount: snapshot.data.length,
                  itemBuilder: (context, index) {
                    return GestureDetector(
                      onTap: () {
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) =>
                                    Albums(snapshot.data[index].id)));
                      },
                      child: Card(
                        child: Column(
                          children: [
                            ListTile(
                                title: Text('${snapshot.data[index].name}'),
                                subtitle:
                                    Text('${snapshot.data[index].email}')),
                          ],
                        ),
                      ),
                    );
                  },
                );
              } else if (snapshot.hasError) {
                return Center(child: Text('${snapshot.error}'));
              }
              return Center(child: CircularProgressIndicator());
            }),
      ),
    );

SERVICE

class PlaceHolderService {
  final baseURL = 'http://jsonplaceholder.typicode.com';

  Future<List<Post>>getPosts() async {
    var response = await http.get('$baseURL/posts');
    if (response.statusCode == 200) {
      var objs = jsonDecode(response.body) as List;
      var posts = objs.map((obj) => Post.fromJson(obj)).toList();
      return posts;
    } else {
      throw Exception('Erro ao buscar posts');
    }
  }

  Future<User> getPerfil() async {
    var response = await http.get('$baseURL/users/1');
    if (response.statusCode == 200) {
      var user = User.fromJson(jsonDecode(response.body));
      return user;
    } else {
      throw Exception('Erro ao buscar perfil do usuário');
    }
  }

  Future<List<Comment>>getComments(int postId) async {
    var response = await http.get('$baseURL/posts/$postId/comments');
    if (response.statusCode == 200) {
      var objs = jsonDecode(response.body) as List;
      var comments = objs.map((obj) => Comment.fromJson(obj)).toList();
      return comments;
    } else {
      throw Exception('Erro ao buscar comentários');
    }
  }
}

MODEL

class Address {
  String street;
  String suite;
  String city;
  String zipcode;

  Address.fromJson(Map<String, dynamic> json)
      : street = json['street'],
        suite = json['suite'],
        city = json['city'],
        zipcode = json['zipcode'];
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.