同时使用Api和Provider

问题描述 投票:0回答:1

我正在为我的个人资料标头中的名称和日期调用 Get api,并且还在我的更新个人资料屏幕中修补 Api 现在我想使用提供程序立即在我的个人资料标头中更新名称现在我如何在我的个人资料标头中使用 get api 和提供程序??


class ProfileHeader extends StatelessWidget {
  const ProfileHeader({super.key});
  @override
  Widget build(BuildContext context) {
    final profileProvider = Provider.of<ProfileProvider>(context);

    return Container(
      width: MediaQuery.of(context).size.width * 0.9,
      padding: const EdgeInsets.all(40.0),
      decoration: BoxDecoration(
        color: Colors.green,
        borderRadius: BorderRadius.circular(16),
      ),
      child: Row(
        children: [
          const CircleAvatar(
            radius: 40,
            backgroundImage: AssetImage('assets/images/image.png'),
          ),
          const SizedBox(width: 16),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                profileProvider.name,
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 4),
              Text(
                'Last Login: ${profileProvider.lastLogin}',
                style: const TextStyle(color: Colors.white, fontSize: 13),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

提供商

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

class ProfileProvider with ChangeNotifier {
  String _name = 'Loading...';
  String _lastLogin = 'Loading...';

  String get name => _name;
  String get lastLogin => _lastLogin;

  Future<void> fetchProfile() async {
    const String url = 'https://api.vezigo.in/v1/app/profile';
    final prefs = await SharedPreferences.getInstance();
    final accessToken = prefs.getString('accessToken');

    try {
      final response = await http.get(
        Uri.parse(url),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer $accessToken',
        },
      );

      if (response.statusCode == 200) {
        final Map<String, dynamic> jsonResponse = json.decode(response.body);
        _name = jsonResponse['data']['name'];
        _lastLogin = jsonResponse['data']['createdAt'];
        notifyListeners();
      } else {
        throw Exception('Failed to load profile');
      }
    } catch (error) {
      _name = 'Error';
      _lastLogin = 'Error';
      notifyListeners();
    }
  }

  Future<void> updateProfile(String newName, String newEmail) async {
    const String url = 'https://api.vezigo.in/v1/app/profile';
    final prefs = await SharedPreferences.getInstance();
    final accessToken = prefs.getString('accessToken');

    try {
      final response = await http.patch(
        Uri.parse(url),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer $accessToken',
        },
        body: json.encode({
          'name': newName,
          'email': newEmail,
        }),
      );

      if (response.statusCode == 200) {
        final responseBody = json.decode(response.body);

        _name = responseBody['data']['name'];
        notifyListeners();

        await prefs.setString('name', _name);
        await prefs.setString('email', responseBody['data']['email']);
      } else {
        throw Exception('Failed to update profile');
      }
    } catch (error) {
      print('Error updating profile: $error');
    }
  }
}

我尝试过,但在我的个人资料标题中的名称和日期都显示正在加载.. enter image description here

flutter dart state-management
1个回答
0
投票

您初始化了

profileProvider
,但没有使用它。构建小部件后,您可以使用
WidgetsBinding.instance.addPostFrameCallback
获取配置文件。

 Widget build(BuildContext context) {
    final profileProvider = Provider.of<ProfileProvider>(context);

    WidgetsBinding.instance.addPostFrameCallback((_) {
      profileProvider.fetchProfile();
    });

并使用

Text
小部件来显示:

Text(
    profileProvider.name,
    style: const TextStyle(
        color: Colors.white,
        fontSize: 20,
        fontWeight: FontWeight.bold,
    ),
),
© www.soinside.com 2019 - 2024. All rights reserved.