0

well i have a little problem with the listview builder , i make a request on a api and i am upposed to display the result depending on the length of the result, it works very well but when i have no data from the api, i have this message from flutter : no suchMethosError:"map" Dynamic call with incorrect number of type arguments Expected 2 actual 1 Receiver instance of 'jsonMap' Arguments:[instance of dynamic)=> historique]

import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:tentative_formulaire_konamicash/pages/post_history.dart';
import 'package:tentative_formulaire_konamicash/pages/test_vfetch.dart';

class gamehistory extends StatefulWidget {
  const gamehistory({
    super.key,
    required this.email,
    required this.password,
  });

  final String password;
  final String email;

  @override
  State<gamehistory> createState() => _gamehistoryState();
}

class _gamehistoryState extends State<gamehistory> {
  Future<void> equipe(String lepgagnant) async {
    var url = Uri.parse('https://konamicash.com/jeux_app');
    var response = await http.post(url, headers: {
      "Accept": "application/json",
      "Access-Control-Allow-Origin": "*"
    }, body: {
      "email": widget.email,
    });
    if (response.statusCode == 200) {
      var retour = jsonDecode(response.body);
      print(retour);
      setState(() {});
    }
  }

  Future<void> contenu() async {
    var url = Uri.parse('https://konamicash.com/vfetch_app');
    var response = await http.post(url, headers: {
      "Accept": "application/json",
      "Access-Control-Allow-Origin": "*"
    }, body: {
      "email": widget.email,
    });

    if (response.statusCode == 200) {
      var reponse = jsonDecode(response.body);
      if (reponse['situation'] == 0) {
        print('no data');
      } else {
        Navigator.push(
          context,
          PageRouteBuilder(
              pageBuilder: (context, animation, secondaryAnimation) =>
                  TestVfetch(mail: widget.email, password: widget.password),
              transitionsBuilder:
                  (context, animation, secondaryAnimation, child) {
                animation =
                    CurvedAnimation(parent: animation, curve: Curves.ease);
                return FadeTransition(
                  opacity: animation,
                  child: child,
                );
              }),
        );
      }
      print(reponse);

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('message'),
        ),
      );
    }
  }

  late Future<List<history>> usersFuture = vfetchdata();
  Future<List<history>> vfetchdata() async {
    final url = Uri.parse('https://konamicash.com/jeux_app');
    final response = await http.post(url, headers: {
      "Accept": "application/json",
      "Access-Control-Allow-Origin": "*"
    }, body: {
      "email": widget.email,
    });

    final body = json.decode(response.body);

    return body.map<history>(history.fromJson).toList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('konami'),
      ),
      body: Center(
        child: FutureBuilder<List<history>>(
            future: usersFuture,
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return const CircularProgressIndicator();
              } else if (snapshot.hasData) {
                final users = snapshot.data!;
                return buildstories(users);
              } else if (snapshot.hasError) {
                return Text('${snapshot.error}');
              } else {
                return const Text('nothing to display');
              }
            }),
      ),
    );
  }
}

Widget buildstories(List<history> users) => ListView.builder(
    itemCount: users.length,
    itemBuilder: (context, index) {
      final user = users[index];

     
      return Card(
        child: ListTile(
          leading: CircleAvatar(
            backgroundImage:
                NetworkImage('https://konamicash.com/${user.image_equipe}'),
          ),
          title: Text('${user.name}  ${user.mail}'),
          subtitle: Text(user.phone),
        ),
      );
    });
//My class history

class history {
  final String name;
  final String mail;
  final String phone;


  final String cote;

  const history(
      {required this.name,
      required this.mail,
      required this.phone,
});

  static history fromJson(json) => history(
      nom: json['name'],
      prenoms: json['mail'],
      numero_de_telephone: json['phone'],
);
}

1 Answer 1

0

Try it

class gamehistory extends StatefulWidget {
  const gamehistory({
    super.key,
    required this.email,
    required this.password,
  });

  final String password;
  final String email;

  @override
  State<gamehistory> createState() => _gamehistoryState();
}

class _gamehistoryState extends State<gamehistory> {
  late Future<List<history>> usersFuture;

  @override
  void initState() {
    super.initState();
    usersFuture = vfetchdata();
  }

  Future<List<history>> vfetchdata() async {
    final url = Uri.parse('https://konamicash.com/jeux_app');
    try {
      final response = await http.post(url, headers: {
        "Accept": "application/json",
        "Access-Control-Allow-Origin": "*"
      }, body: {
        "email": widget.email,
      });

      // Print the raw response for debugging
      print('Response body: ${response.body}');

      if (response.statusCode == 200) {
        // Try to parse the response body
        dynamic body = json.decode(response.body);

        // Handle different possible response formats
        if (body == null) {
          return [];
        }

        // If body is a list, map directly
        if (body is List) {
          return body.map<history>((item) => 
            item is Map<String, dynamic> 
              ? history.fromJson(item) 
              : history.empty()
          ).toList();
        }

        // If body is a map, check for a nested list
        if (body is Map<String, dynamic>) {
          // Try to extract a list from common key names
          final List? dataList = body['data'] ?? body['results'] ?? body['items'];
          
          if (dataList != null) {
            return dataList.map<history>((item) => 
              item is Map<String, dynamic> 
                ? history.fromJson(item) 
                : history.empty()
            ).toList();
          }
        }

        // If no recognizable list structure is found
        return [];
      } else {
        // Handle non-200 status code
        print('Error: ${response.statusCode}');
        return [];
      }
    } catch (e) {
      // Catch and log any exceptions during the API call
      print('Exception in vfetchdata: $e');
      return [];
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('konami'),
      ),
      body: Center(
        child: FutureBuilder<List<history>>(
          future: usersFuture,
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const CircularProgressIndicator();
            } else if (snapshot.hasError) {
              return Text('Error: ${snapshot.error}');
            } else if (snapshot.hasData && snapshot.data!.isNotEmpty) {
              final users = snapshot.data!;
              return buildstories(users);
            } else {
              return const Text('No data available');
            }
          },
        ),
      ),
    );
  }
}

Widget buildstories(List<history> users) => ListView.builder(
  itemCount: users.length,
  itemBuilder: (context, index) {
    final user = users[index];
    return Card(
      child: ListTile(
        leading: CircleAvatar(
          backgroundImage: NetworkImage('https://konamicash.com/${user.image_equipe}'),
        ),
        title: Text('${user.name}  ${user.mail}'),
        subtitle: Text(user.phone),
      ),
    );
  }
);

class history {
  final String name;
  final String mail;
  final String phone;
  final String image_equipe;
  final String cote;

  const history({
    required this.name,
    required this.mail,
    required this.phone,
    required this.image_equipe,
    required this.cote,
  });

  // Factory constructor for empty/default history
  factory history.empty() => history(
    name: '',
    mail: '',
    phone: '',
    image_equipe: '',
    cote: '',
  );

  // Robust fromJson method
  static history fromJson(Map<String, dynamic> json) {
    return history(
      name: json['name']?.toString() ?? '',
      mail: json['mail']?.toString() ?? '',
      phone: json['phone']?.toString() ?? '',
      image_equipe: json['image_equipe']?.toString() ?? '',
      cote: json['cote']?.toString() ?? '',
    );
  }
}

1
  • hi thank you for your help, well it works i do have the "no data avaible" message but even when i have data i have the same message... and when i use my code the datas are displayed Commented 2 hours ago

Not the answer you're looking for? Browse other questions tagged or ask your own question.