Skip to content
Advertisement

How to fix The following _CastError was thrown building: type ‘Future’ is not a subtype of type ‘List’ in type cast

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

class Gallery extends StatefulWidget {

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

}

class _GalleryState extends State<Gallery> {

pic() async {

var url = "http://120.76.247.131:8081/findAllImages";
var response = await http.get(Uri.parse(url));
return json.decode(response.body);
}
@override
void initState() {
super.initState();
pic();
 }
@override
Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(
    title: Text('Gallery'),

  ),

  body: FutureBuilder(
    future : pic(),
    builder: (context, snapshot) {
      if (snapshot.hasError) print(snapshot.error);
      return snapshot.hasData
          ? ListView.builder(
          itemCount:2,
          itemBuilder: (context, index) {
            List list = pic() as List;
            return Card(
                child: ListTile(
                title: Container(
                width: 100,
                height: 100,
                child: Image.network(
                "http://120.76.247.131:8081/findAllImages/%7Blist[index][%22image%22]%7D%22)"
            ),
            ),
            ));
          })
          : Center(
        child: CircularProgressIndicator(),
      );
    },
  ),
);
  }
  }

I had tried to add behind the future and it doesn’t solve the problem. Moreover, there is a problem with the itemcount, so I left it with a number instead of add snapshot.data!.length() because I am not sure why there is an error with snapshot.data!.length() for itemcount.

Advertisement

Answer

Here is full working code.

At first because pic() returns Future, you need to use ‘await’ or ‘then’ to get a response.
https://dart.dev/codelabs/async-await

Because of that, below sentence cause error as you provided.
But because it is not necessary in this case, I get rid of this.

List list = pic() as List;

If you want use pic() method, just call like below.
(But in this case, you cannot call like this.)

List list = await pic()

You’ve already used ‘FutureBuilder’, you don’t need to call pic() again.
You just use snapdata’s data incase of snapdata has a data.

enter image description here

import 'dart:convert';

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

void main() {
  print('onStart');
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: Gallery(),
    );
  }
}

class Gallery extends StatefulWidget {
  @override
  _GalleryState createState() => _GalleryState();
}

class _GalleryState extends State<Gallery> {
  pic() async {
    var url = "http://120.76.247.131:8081/findAllImages";
    var response = await http.get(Uri.parse(url));
    return json.decode(response.body);
  }

  @override
  void initState() {
    super.initState();
    pic();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Gallery'),
      ),
      body: FutureBuilder(
        future: pic(),
        builder: (context, snapshot) {
          if (snapshot.hasError) print(snapshot.error);
          return snapshot.hasData
              ? ListView.builder(
                  itemCount: (snapshot.data! as Map)['data'].length,
                  itemBuilder: (context, index) {
                    // List list = pic() as List;
                    print((snapshot.data! as Map)['data'][index]);
                    return Card(
                        child: ListTile(
                      title: Container(
                        width: 100,
                        height: 100,
                        child: Image.network(
                            (snapshot.data! as Map)['data'][index]['image']),
                      ),
                    ));
                  })
              : Center(
                  child: CircularProgressIndicator(),
                );
        },
      ),
    );
  }
}

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement