Using Api and provider together

I am calling Get api for name and date in my profile header and also patch Api in my update profile screen now i want to use provider for upadating name immediately in my profile header now how can i use get api and provider in my profile header ??

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>
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),
),
],
),
],
),
);
}
}
</code>
<code> 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), ), ], ), ], ), ); } } </code>

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),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

Provider

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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');
}
}
}
</code>
<code>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'); } } } </code>
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');
    }
  }
}

I tried but in my profile header in both name and date there is showing loading ..

You initialized profileProvider, but are not using it. You can use WidgetsBinding.instance.addPostFrameCallback to fetch profile once the widget is built.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> Widget build(BuildContext context) {
final profileProvider = Provider.of<ProfileProvider>(context);
WidgetsBinding.instance.addPostFrameCallback((_) {
profileProvider.fetchProfile();
});
</code>
<code> Widget build(BuildContext context) { final profileProvider = Provider.of<ProfileProvider>(context); WidgetsBinding.instance.addPostFrameCallback((_) { profileProvider.fetchProfile(); }); </code>
 Widget build(BuildContext context) {
    final profileProvider = Provider.of<ProfileProvider>(context);

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

and use the Text widget to display:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>Text(
profileProvider.name,
style: const TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
</code>
<code>Text( profileProvider.name, style: const TextStyle( color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold, ), ), </code>
Text(
    profileProvider.name,
    style: const TextStyle(
        color: Colors.white,
        fontSize: 20,
        fontWeight: FontWeight.bold,
    ),
),

Additionally, I’m guessing you already added the provider to your main:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>ChangeNotifierProvider(
create: (context) => ProfileProvider(),
</code>
<code>ChangeNotifierProvider( create: (context) => ProfileProvider(), </code>
ChangeNotifierProvider(
      create: (context) => ProfileProvider(),

0

main.dart

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> MultiProvider(
providers: [
ChangeNotifierProvider<DemoProvider>(
create: (context) => DemoProvider(),
),
ChangeNotifierProvider<ProfileProvider>(
create: (context) => ProfileProvider(),
)
],
child: MaterialApp(
home: const ProfileHeader(),
),
);
</code>
<code> MultiProvider( providers: [ ChangeNotifierProvider<DemoProvider>( create: (context) => DemoProvider(), ), ChangeNotifierProvider<ProfileProvider>( create: (context) => ProfileProvider(), ) ], child: MaterialApp( home: const ProfileHeader(), ), ); </code>
 MultiProvider(
                  providers: [
                    ChangeNotifierProvider<DemoProvider>(
                      create: (context) => DemoProvider(),
                    ),
                    ChangeNotifierProvider<ProfileProvider>(
                      create: (context) => ProfileProvider(),
                    )
                  ],
                  child: MaterialApp(
             home: const ProfileHeader(),
                  ),
                );

wrap both text widget inside the Consumer widget,

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>Consumer<ProfileProvider>(
builder: (context, value, child) {
return Column(
children:[
Text(profileProvider.value.yourVariableName
),
Text('Last Login: ${profileProvider.value.lastLogin}'),
]);
},
),
</code>
<code>Consumer<ProfileProvider>( builder: (context, value, child) { return Column( children:[ Text(profileProvider.value.yourVariableName ), Text('Last Login: ${profileProvider.value.lastLogin}'), ]); }, ), </code>
Consumer<ProfileProvider>(
                  builder: (context, value, child) {
                    return Column(
                       children:[
                   Text(profileProvider.value.yourVariableName
                    ),
                Text('Last Login: ${profileProvider.value.lastLogin}'),
                   ]);
                  },
                ),

New contributor

Akshay payya is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật