在flutter中发出获取API请求时出错

zy1mlcev  于 2022-12-05  发布在  Flutter
关注(0)|答案(1)|浏览(258)

这是我的homeView代码调用从main.dart,我不知道是什么错误,我尝试了很多次,但没有得到解决,我试图调试,但我不知道为什么没有msg打印在控制台或运行选项卡.我正在采取JSON占位符演示api从网站和创建一个模型从quicktype,但最后我无法检查为什么我没有收到任何回应。API也检查在网站和 Postman 它的工作,但在代码没有得到任何请求,请帮助

import 'dart:convert';
    import 'package:flutter/material.dart';
    import 'package:http/http.dart' as http;
    import '../models/userModel.dart';
    
    class HomeView extends StatefulWidget {
      const HomeView({Key? key}) : super(key: key);
    
      @override
      State<HomeView> createState() => _HomeViewState();
    }
    
    class _HomeViewState extends State<HomeView> {
      //create an empty array or list
      List<Users> userDetails = [];
    
      //future response from server (get users details from api)
      Future<List<Users>> getUsers() async {
        print("api method calling");
        final response =
            await http.get(Uri.parse("https://jsonplaceholder.typicode.com/users"),);
        print('api response check');
        var data = jsonDecode(response.body.toString());
        print('api data received');
        if (response.statusCode == 200) {
    
    
          for (Map<String, dynamic> index in data) {
            userDetails.add(Users.fromJson(index));
          }
          return userDetails;
        } else {
          return userDetails;
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return FutureBuilder(
            future: getUsers(),
            builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          print('no connection error');
          if (snapshot.hasData) {
            print('snapshot has data');
            return ListView.builder(
                itemCount: 1,
                itemBuilder: (context, index) {
                  return Container(
                    margin: const EdgeInsets.all(10),
                    height: 100,
                    color: Colors.greenAccent,
                    padding: const EdgeInsets.symmetric(
                        vertical: 10, horizontal: 20),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: const [
                        Text('User Id : data'),
                        Text('User Id : data'),
                        Text('User Id : data'),
                        Text('User Id : data'),
                      ],
                    ),
                  );
                });
          } else {
            print('snapshot has no data');
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
        }else{
        return Center(
            child: Text("connection error"),
          );
        }
            });
    
      }
    }

这是我的模型

// To parse this JSON data, do
//
//     final users = usersFromJson(jsonString);

import 'dart:convert';

List<Users> usersFromJson(String str) => List<Users>.from(json.decode(str).map((x) => Users.fromJson(x)));

String usersToJson(List<Users> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Users {
  Users({
    required this.id,
    required this.name,
    required this.username,
    required this.email,
    required this.address,
    required this.phone,
    required this.website,
    required this.company,
  });

  int id;
  String name;
  String username;
  String email;
  Address address;
  String phone;
  String website;
  Company company;

  factory Users.fromJson(Map<String, dynamic> json) => Users(
    id: json["id"],
    name: json["name"],
    username: json["username"],
    email: json["email"],
    address: Address.fromJson(json["address"]),
    phone: json["phone"],
    website: json["website"],
    company: Company.fromJson(json["company"]),
  );

  Map<String, dynamic> toJson() => {
    "id": id,
    "name": name,
    "username": username,
    "email": email,
    "address": address.toJson(),
    "phone": phone,
    "website": website,
    "company": company.toJson(),
  };
}

class Address {
  Address({
    required this.street,
    required this.suite,
    required this.city,
    required this.zipcode,
    required this.geo,
  });

  String street;
  String suite;
  String city;
  String zipcode;
  Geo geo;

  factory Address.fromJson(Map<String, dynamic> json) => Address(
    street: json["street"],
    suite: json["suite"],
    city: json["city"],
    zipcode: json["zipcode"],
    geo: Geo.fromJson(json["geo"]),
  );

  Map<String, dynamic> toJson() => {
    "street": street,
    "suite": suite,
    "city": city,
    "zipcode": zipcode,
    "geo": geo.toJson(),
  };
}

class Geo {
  Geo({
    required this.lat,
    required this.lng,
  });

  String lat;
  String lng;

  factory Geo.fromJson(Map<String, dynamic> json) => Geo(
    lat: json["lat"],
    lng: json["lng"],
  );

  Map<String, dynamic> toJson() => {
    "lat": lat,
    "lng": lng,
  };
}

class Company {
  Company({
    required this.name,
    required this.catchPhrase,
    required this.bs,
  });

  String name;
  String catchPhrase;
  String bs;

  factory Company.fromJson(Map<String, dynamic> json) => Company(
    name: json["name"],
    catchPhrase: json["catchPhrase"],
    bs: json["bs"],
  );

  Map<String, dynamic> toJson() => {
    "name": name,
    "catchPhrase": catchPhrase,
    "bs": bs,
  };
}

以下是main.dart文件

import 'package:flutter/material.dart';
import 'package:responsive_login_ui/views/home_view.dart';


void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(title: Text('User Data From Api'),),
        body:  HomeView()
      ),
    );
  }
}
atmip9wb

atmip9wb1#

在HomeView页面中添加以下行

late Future<List<Users>> userAlbum;

@override
void initState() {
 super.initState();
 userAlbum = getUsers();
}

和变化

future: getUsers(),

future: userAlbum,

你的代码不能工作的主要原因可能是future被调用了。上面的代码片段来自flutter中HTTP请求的docs
希望这对你有帮助。快乐编码:)

相关问题