How can I resolve "The argument type 'String' can't be assigned to the parameter type 'int' " - Flutter
Asked Answered
P

13

48

I'm trying to fetch data Online Using HTTP GET with Flutter SDK. I'm trying with this code https://github.com/RaglandCodes/Flutter-basic-API/blob/master/lib/main.dart but it is showing an error about data type that's

The argument type 'String' can't be assigned to the parameter type 'int'

Here's Error part

new Card(
     child: new Container(
     child: new Text(data[index]['name']), //error red underlying with 'name'
     padding: EdgeInsets.all(20),
     ),

Here's my main.dart

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'dart:async';

void main() {
  runApp(new MaterialApp(home: new HomePage(),));
}

 class HomePage extends StatefulWidget {
   @override
   _HomePageState createState() => _HomePageState();
 }

 class _HomePageState extends State<HomePage> {

  String url="https://swapi.co/api/people/";
  List<String> data;

  /*onCreate*/
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    getJSONData(); //method
  }

   @override
   Widget build(BuildContext context) {
     return new Scaffold(
       appBar: AppBar(
           title: Text("my JSON app")
       ),
       body: new ListView.builder(
        // itemCount: 1,
         //itemCount: data==null ? 0 :data.length ,
         itemCount: data == null ? 0 : data.length,

         itemBuilder: (BuildContext context, int index){
           return new Container(
             child: new Center(
               child: new Column(
                 crossAxisAlignment: CrossAxisAlignment.stretch, 
                 children: <Widget>[
                   new Card(
                     child: new Container(
                       child: new Text(data[index]['name']),
                       padding: EdgeInsets.all(20),
                     ),
                   )
                 ],
               ),
             ),
           );
         },
       ),
     );
   }

   /*method*/ //RT is Future<String>
  Future<String> getJSONData() async{
    var response =await http.get(
      Uri.encodeFull(url),
      headers: {"Accept": "application/json"}
    );
   print(response.body);
   debugPrint(response.body);

    setState(() {
      var convertDataToJson= json.decode(response.body);
      data=convertDataToJson['results'];
    });

    return "Success";
  }
 }
Polymerous answered 5/5, 2019 at 19:48 Comment(1)
data is of type List<String>. What is data[index]['name'] supposed to be?Frisket
M
21

You have to set data variable to List type.

That's should work:

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'dart:async';

void main() {
  runApp(new MaterialApp(
    home: new HomePage(),
  ));
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String url = "https://swapi.co/api/people/";
  List data;

  /*onCreate*/
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    getJSONData(); //method
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(title: Text("my JSON app")),
      body: new ListView.builder(
        // itemCount: 1,
        //itemCount: data==null ? 0 :data.length ,
        itemCount: data == null ? 0 : data.length,

        itemBuilder: (BuildContext context, int index) {
          return new Container(
            child: new Center(
              child: new Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
                  new Card(
                    child: new Container(
                      child: new Text(data[index]['name'] ?? ''),
                      padding: EdgeInsets.all(20),
                    ),
                  )
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  /*method*/ //RT is Future<String>
  Future<String> getJSONData() async {
    var response = await http
        .get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
    print(response.body);
    debugPrint(response.body);

    setState(() {
      var convertDataToJson = json.decode(response.body);
      data = convertDataToJson['results'];
    });

    return "Success";
  }
}
Mcafee answered 5/5, 2019 at 20:12 Comment(2)
This answer would be more complete if you explained whyOlives
The argument type 'String' can't be assigned to the parameter type 'Uri'.Zacarias
S
81

That's worked for me

http.get(Uri.https('https://swapi.co', 'api/people'));

or

http.get(Uri.parse('https://swapi.co/api/people'));
Sacerdotal answered 5/3, 2021 at 14:39 Comment(1)
This is a valid answer for those using http: 0.13.0 and above. Here is the changelog which mentions this as a breaking change: pub.dev/packages/http/changelog#0130-nullsafety0Chrystalchryste
L
35

If you add .toString() the error will disappear:

Text(data[index]['name'].toString())

good

Linkage answered 14/8, 2021 at 18:53 Comment(0)
M
21

You have to set data variable to List type.

That's should work:

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'dart:async';

void main() {
  runApp(new MaterialApp(
    home: new HomePage(),
  ));
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String url = "https://swapi.co/api/people/";
  List data;

  /*onCreate*/
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    getJSONData(); //method
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(title: Text("my JSON app")),
      body: new ListView.builder(
        // itemCount: 1,
        //itemCount: data==null ? 0 :data.length ,
        itemCount: data == null ? 0 : data.length,

        itemBuilder: (BuildContext context, int index) {
          return new Container(
            child: new Center(
              child: new Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
                  new Card(
                    child: new Container(
                      child: new Text(data[index]['name'] ?? ''),
                      padding: EdgeInsets.all(20),
                    ),
                  )
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  /*method*/ //RT is Future<String>
  Future<String> getJSONData() async {
    var response = await http
        .get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
    print(response.body);
    debugPrint(response.body);

    setState(() {
      var convertDataToJson = json.decode(response.body);
      data = convertDataToJson['results'];
    });

    return "Success";
  }
}
Mcafee answered 5/5, 2019 at 20:12 Comment(2)
This answer would be more complete if you explained whyOlives
The argument type 'String' can't be assigned to the parameter type 'Uri'.Zacarias
P
15

The reason is that http.get can't work with strings anymore. You need to use Uri to parse the HTTP address.

I had the same issue which I fixed it with this approach:

var url = Uri.parse("https://your_api_link");

then call it like this (attaching the http):

http.Response response = await http.get(url);

This should work.

Pufahl answered 29/3, 2021 at 18:6 Comment(1)
Well, I don't really know the reason, maybe String could no longer handle URL values due to the async pattern in retrieving the url data. But I think someone else could have a better reason here.Pufahl
H
4

var response = await http.get(Uri.parse(url));
Hoelscher answered 22/3, 2021 at 17:5 Comment(1)
Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you’ve made.Seyler
C
4

That's worked for me

 http.Response respobse= await 
      http.get(Uri.parse("https://jsonplaceholder.typicode.com/photos"));
    
    Uri.parse(json Url);

use this.

Charlot answered 23/5, 2021 at 20:4 Comment(0)
M
3

This one will work

String url = '$api?lat=$latitude&lon=$longitude&APPID=$appId';
 http.Response response = await http.get(Uri.parse(url));
Mendelssohn answered 22/6, 2021 at 6:11 Comment(0)
U
3

if you will simply add .toSting() to your lists like below it will remove the error.

new Card(
     child: new Container(
     child: new Text(data[index]['name'].toString()), //This line
     padding: EdgeInsets.all(20),
),
Usance answered 8/1, 2022 at 1:14 Comment(1)
Such answer already existsSacker
T
2

That's worked for me

void getData() async {
  Response response = await 
  http.get(Uri.parse("https://jsonplaceholder.typicode.com/todos/1"));
  print(response.body);
}
Triazine answered 14/5, 2021 at 6:3 Comment(0)
L
1

If you add ".toString()" the error will disappear:

new Text(data[index]['name'].toString()),

So:

new Card(
     child: new Container(
     child: new Text(data[index]['name'].toString()), //you'll no longer get an error
     padding: EdgeInsets.all(20),
     ),
Lm answered 22/5, 2021 at 15:28 Comment(0)
B
0

u can use this way

Future<http.Response> fetchAlbum() {return http.get(Uri.https('jsonplaceholder.typicode.com', 'albums/1'));}
Baldwin answered 9/3, 2021 at 23:53 Comment(0)
F
0

if you are using pdf package your want to delete import 'dart:html'; and use import 'dart:io';
It's worked for me, Have a good day :-)

Fusain answered 26/3, 2022 at 7:26 Comment(0)
D
0
Future<String> getSWData() async 
{

   // String res = await http.get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
    http.Response res = await http.get(url);

     // var res =   await http.get(Uri.https('http://3.255.7.222:8084/sipService/supplerMaster/v1/getSupplierMasterList', 'api/people'));

    var resBody = json.decode(res.body);
    setState(() {
      data = resBody;
    });
    print(resBody);
    return "Sucess";
  }
Denaedenarius answered 29/9, 2022 at 17:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.