flutter 当我在使用GetX状态时执行“热重启”时,我无法在屏幕上呈现数据

tquggr8v  于 2023-02-05  发布在  Flutter
关注(0)|答案(1)|浏览(102)

我的模型

class UserModel {
  final int id;
  final String email;
  final String first_name;
  final String last_name;
  final String avatar;

  UserModel({
    required this.id,
    required this.email,
    required this.first_name,
    required this.last_name,
    required this.avatar,
  });

  factory UserModel.fromJson(Map<String, dynamic> json) {
    return UserModel(
      id: json['id'],
      email: json['email'],
      avatar: json['avatar'],
      first_name: json['first_name'],
      last_name: json['last_name'],
    );
  }

}

美阿皮

class ApiService {
  final Uri url = Uri.parse('https://reqres.in/api/users?page=2');

  Future<List<UserModel?>?> getApi() async {
    try {
      var response = await http.get(url);
      var responeOfData = jsonDecode(response.body);

      print('responeOfData: ${responeOfData["data"]}');

      if (response.statusCode == 200) {
        print('status code 200 geldi');

        List<UserModel?> users = [];

        for (var user in responeOfData["data"]) {
          print('user: $user');
          users.add(UserModel.fromJson(user));
        }

        return users;
      } else {
        print('error kodu: ${response.statusCode}');
      }
    } catch (error) {
      print('Api serviste error oluştu: $error');
    }
    return null;
  }
}

主计长

class UserModelController extends GetxController {
  List<UserModel?>? userModelList = <UserModel?>[].obs;

  ApiService controller = Get.put(ApiService());

  Future<void> getUserModels() async {
    try {
      userModelList = (await controller.getApi())!;
      print('userModelList length: ${userModelList?.length}');
    } catch (error) {
      print('error UserModelController: $error');
    }
  }
}

我的小工具

void main() => runApp(GetMaterialApp(home: ObxListView()));

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

  UserModelController controller = Get.put(UserModelController());

  @override
  Widget build(BuildContext context) {

    controller.getUserModels().reactive;

    return Scaffold(
      appBar: AppBar(
       title: const Text('GetX List'),
       centerTitle: true,
      ),
      body: Center(
        child: Column(
          children: [
            Obx(() =>
                Flexible(
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: ListView.builder(
                      itemCount: controller.userModelList?.length,
                      itemBuilder: (context, index) {
                        return Card(
                          shape: const OutlineInputBorder(
                              borderRadius: BorderRadius.all(Radius.circular(10))
                          ),
                          margin: const EdgeInsets.all(2),
                          child: ListTile(
                            title: Row(
                              children: [
                                Text('Name: ${controller.userModelList?[index]?.first_name}'),
                                const SizedBox(width: 10),
                                Text('${controller.userModelList?[index]?.last_name}'),
                              ],
                            ),
                            subtitle: Text('${controller.userModelList?[index]?.email}'),
                            leading: CircleAvatar(
                              backgroundImage: NetworkImage('${controller.userModelList?[index]?.avatar}'),
                            ),
                          ),
                        );
                      },
                    ),
                  ),
                ),
            ),
            ElevatedButton(onPressed: () {
              //controller.getUserModels();
              print('length: ${controller.userModelList?.length}');
              print('name ${controller.userModelList?[0]?.first_name}');
              print('name ${controller.userModelList?[1]?.first_name}');
            }, child: const Text('Test Button')),
          ],
        ),
      ),
    );
  }
}

大家好,这将是我在stackoverflow上的第一篇文章。
当我使用热重启时,我不能在屏幕上绘制数据。但是当我热重新加载时,数据就像我发送的下面的截图一样。
于是我搜索了一下论坛,遇到了有类似问题的朋友,但找不到适合自己的解决方案。
如果有人能给我解释一下问题的根源,我将不胜感激。谢谢:)
enter image description here

v7pvogib

v7pvogib1#

import 'dart:convert';

import 'package:get/get.dart';
import 'package:testing_carts/user_model.dart';
import 'package:http/http.dart' as http;

class GetXApiService extends GetxController {
  final Uri url = Uri.parse('https://reqres.in/api/users?page=2');
  List<UserModel?> users = <UserModel?>[].obs;
  var isLoading = false.obs;

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    getApi();
  }

  Future<void> getApi() async {
    try {
      isLoading.value = true;
      var response = await http.get(url);
      var responeOfData = jsonDecode(response.body);

      print('responeOfData: ${responeOfData["data"]}');

      if (response.statusCode == 200) {
        print('status code 200');

        for (var user in responeOfData["data"]) {
          print('user: $user');
          users.add(UserModel.fromJson(user));
        }
      } else {
        print('error kodu: ${response.statusCode}');
      }
    } catch (error) {
      print('Api serviste error oluştu: $error');
    } finally {
      isLoading.value = false;
    }
  }
}

我修复了这个问题,我想分享解决方案。有些人可能会遇到这个错误。

相关问题