Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'String' not subtype of 'int' flutter

Tags:

flutter

dart

this is my first flutter JSON example, I tried to fetch data from the json link and display the titles as list view

I used this code to write mine with some changes .. in the link he has results array in mine I haven't so I left the data = resBody[" "]; empty is that right?

also, I got this error with the flutter HTTP request and don't really what to do

any help, please?

Dart Error: Unhandled exception:
 type 'String' is not a subtype of type 'int' of 'index'

this is my code

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

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

class ToDo extends StatefulWidget {
  @override
  ToDoState createState() => ToDoState();
}

class ToDoState extends State<ToDo> {
  final String url = "https://jsonplaceholder.typicode.com/todos";
  List data;

  Future<String> getTitle() async {
    var res = await http
        .get(Uri.encodeFull(url), headers: {"Accept": "application/json"});

    setState(() {
      var resBody = json.decode(res.body);
      data = resBody[" "];
    });

    return "Success!";
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Title List"),
        backgroundColor: Colors.amber,
      ),
      body: ListView.builder(
        itemCount: data == null ? 0 : data.length,
        itemBuilder: (BuildContext context, int index) {
          return new Container(
            child: Center(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
                  Card(
                    child: Container(
                        padding: EdgeInsets.all(15.0),
                        child: Row(
                          children: <Widget>[
                            Text("Title: "),
                            Text(data[index]["title"],
                                style: TextStyle(
                                    fontSize: 18.0, color: Colors.black87)),
                          ],
                        )),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    this.getTitle();
  }
}
like image 634
Tabarek Ghassan Avatar asked Jan 14 '19 10:01

Tabarek Ghassan


1 Answers

Your getTitle methods needs to be changed to the following:

Future<String> getTitle() async {
    var res = await http
        .get(Uri.encodeFull(url), headers: {"Accept": "application/json"});

    setState(() {
      var resBody = json.decode(res.body);
      data = resBody; //This line changed from data = resBody[" "];
    });

    return "Success!";
}
like image 132
Jordan Davies Avatar answered Nov 03 '22 07:11

Jordan Davies