Flutter 从 Api 获取 Userinfo 并在任何地方使用。请帮我

Posted

技术标签:

【中文标题】Flutter 从 Api 获取 Userinfo 并在任何地方使用。请帮我【英文标题】:Flutter Get Userinfo from Api and use it everywhere. Please help me 【发布时间】:2022-01-20 23:34:31 【问题描述】:

我是 Flutter 新手,需要一些帮助。我想使用抽屉中的用户名,但无法访问数据。我总是得到一个 'Future 的实例。 如何在身份验证后访问名字,姓氏......然后我如何在我的代码中的任何地方使用它,例如在 mydrawer 中被显示?请帮帮我

    LoginResponseModel.fromJson(json.decode(str));

class LoginResponseModel 
  LoginResponseModel(
    required this.message,
    required this.data,
  );
  late final String message;
  late final Data data;

  LoginResponseModel.fromJson(Map<String, dynamic> json) 
    message = json['message'];
    data = Data.fromJson(json['data']);
  

  Map<String, dynamic> toJson() 
    final _data = <String, dynamic>;
    _data['message'] = message;
    _data['data'] = data.toJson();
    return _data;
  


class Data 
  Data(
    required this.username,
    required this.email,
    required this.date,
    required this.id,
    required this.token,
  );
  late final String username;
  late final String email;
  late final String date;
  late final String id;
  late final String token;

  Data.fromJson(Map<String, dynamic> json) 
    username = json['username'];
    email = json['email'];
    date = json['date'];
    id = json['id'];
    token = json['token'];
  

  Map<String, dynamic> toJson() 
    final _data = <String, dynamic>;
    _data['username'] = username;
    _data['email'] = email;
    _data['date'] = date;
    _data['id'] = id;
    _data['token'] = token;
    return _data;
  

应该存储数据的共享服务!

  static Future<LoginResponseModel?> loginDetails() async 
    var isKeyExist =
        await APICacheManager().isAPICacheKeyExist("login_details");

    if (isKeyExist) 
      var cacheData = await APICacheManager().getCacheData("login_details");

      return loginResponseJson(cacheData.syncData);
    
  

我测试了登录详细信息中存储了哪些数据的主页,但在控制台中它的schown: I/flutter (5992): 'Future'的实例


import 'package:flutter/material.dart';
import 'package:join_coins/pages/pay.dart';
import 'package:join_coins/pages/portfolio.dart';
import 'package:join_coins/pages/trade.dart';
import 'package:join_coins/pages/withdraw.dart';
import 'package:join_coins/services/api_service.dart';
import 'package:join_coins/services/shared_service.dart';
import 'package:join_coins/widgets/appbar_widget.dart';
import 'package:join_coins/widgets/navigation_drawer_widget.dart';

class HomePage extends StatefulWidget 
  const HomePage(Key? key) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();


class _HomePageState extends State<HomePage> 
  int _currentIndex = 0;
  final screens = [HomePage(), Portfolio(), Withdraw(), Trade(), Pay()];

  var test = SharedService.loginDetails();

  @override
  Widget build(BuildContext context) => Scaffold(
        appBar: MyAppBar(
          title: "Homie",
        ),
        backgroundColor: Colors.white,
        body: userProfile(),
        drawer: NavigationDrawerWidget(),
        bottomNavigationBar: BottomNavigationBar(
          type: BottomNavigationBarType.fixed,
          backgroundColor: Colors.black,
          selectedItemColor: const Color.fromRGBO(0, 82, 255, 1.0),
          unselectedItemColor: Colors.white,
          iconSize: 30,
          elevation: 15,
          selectedFontSize: 12,
          currentIndex: _currentIndex,
          onTap: (index) => setState(() => _currentIndex = index),
          items: const <BottomNavigationBarItem>[
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              label: 'Startseite',
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.pie_chart_outline),
              label: 'Portfolio',
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.sync),
              label: '',
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.trending_up),
              label: 'Handeln',
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.toll),
              label: 'Bezahlen',
            ),
          ],
        ),
      );


Widget userProfile() 
  return FutureBuilder(
    future: APIService.getUserProfile(),
    builder: (BuildContext context, AsyncSnapshot<String> model) 
      if (model.hasData) 
        print(SharedService.loginDetails());
        return Center(
            child: Text(
          model.data!,
          style: TextStyle(fontSize: 25, color: Colors.red),
        ));
      
      return const Center(
        child: CircularProgressIndicator(),
      );
    ,
  );

我想使用来自 api(firstname,lastname,username...) 的数据的 Drawer 类被显示出来。

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:join_coins/pages/home.dart';
import 'package:join_coins/services/shared_service.dart';
import 'package:snippet_coder_utils/FormHelper.dart';
import 'package:snippet_coder_utils/hex_color.dart';

class NavigationDrawerWidget extends StatelessWidget 
  final padding = EdgeInsets.symmetric(horizontal: 20, vertical: 80);
  final firstName = "test";
  final lastName = "test";
  final userImage =
      "https://www.pinclipart.com/picdir/middle/148-1486972_mystery-man-avatar-circle-clipart.png";

  NavigationDrawerWidget(Key? key, firstName, lastName, userImage)
      : super(key: key);

  @override
  Widget build(BuildContext context) 
    return Drawer(
      child: Material(
        color: Colors.grey[850],
        child: ListView(
          padding: padding,
          children: <Widget>[
            buildHeader(
              userImage: userImage,
              firstName: firstName,
              lastName: lastName,
            ),
            const SizedBox(height: 20),
            buildMenuItem(
              text: "Kennenlernen und verdienen",
              icon: Icons.auto_awesome_outlined,
              onClicked: () => selectedItem(context, 0),
            ),
            const SizedBox(height: 20),
            buildMenuItem(
              text: "Coins erhalten",
              icon: CupertinoIcons.percent,
              onClicked: () => selectedItem(context, 1),
            ),
            const SizedBox(height: 20),
            buildMenuItem(
              text: "Freunde einladen",
              icon: Icons.person_add_alt_1_outlined,
              onClicked: () => selectedItem(context, 2),
            ),
            const SizedBox(height: 20),
            buildMenuItem(
              text: "Geschenk senden",
              icon: CupertinoIcons.gift,
              onClicked: () => selectedItem(context, 3),
            ),
            const SizedBox(height: 200),
            new Center(
              child: FormHelper.submitButton(
                "Abmelden",
                () 
                  SharedService.logout(context);
                ,
                width: 450,
                btnColor: HexColor("#00ff001C"),
                borderColor: Colors.grey,
                txtColor: Colors.white,
                borderRadius: 10,
                fontWeight: FontWeight.bold,
              ),
            ),
          ],
        ),
      ),
    );
  


buildHeader(
  required String firstName,
  required String lastName,
  required String userImage,
  VoidCallback? onClicked,
) =>
    InkWell(
      onTap: onClicked,
      child: Container(
        child: Row(
          children: [
            CircleAvatar(
              radius: 30,
              backgroundImage: NetworkImage(userImage),
            )
          ],
        ),
      ),
    );

void selectedItem(BuildContext context, int index) 
  Navigator.of(context).pop();

  switch (index) 
    case 0:
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) => HomePage(),
      ));
      break;
    case 1:
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) => HomePage(),
      ));
      break;
    case 2:
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) => HomePage(),
      ));
      break;
    case 3:
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) => HomePage(),
      ));
      break;
  


Widget buildMenuItem(
  required String text,
  required IconData icon,
  VoidCallback? onClicked,
) 
  final color = Colors.white;
  return ListTile(
    leading: Icon(icon, color: color),
    title: Text(
      text,
      style: TextStyle(color: color, fontWeight: FontWeight.bold, fontSize: 20),
    ),
    onTap: onClicked,
  );

这里是api服务getUserProfile,但是responsebody 我得到的是 ,,授权用户”

static Future<String> getUserProfile() async 
    var loginDetails = await SharedService.loginDetails();

    Map<String, String> requestHeaders = 
      'Content-Type': 'application/json',
      'Authorization': 'Basic $loginDetails!.data.token'
    ;

    var url = Uri.http(Config.apiURL, Config.userProfileAPI);

    var response = await client.get(
      url,
      headers: requestHeaders,
    );

    if (response.statusCode == 200) 
      return response.body;
     else 
      return "";
    

【问题讨论】:

【参考方案1】:

您可以尝试使用http 包从 API 获取数据

【讨论】:

好的,你能告诉我具体怎么做吗?

以上是关于Flutter 从 Api 获取 Userinfo 并在任何地方使用。请帮我的主要内容,如果未能解决你的问题,请参考以下文章

Flutter - 无法通过 http.get 从 api 获取数据

如何使用 dart/flutter 从 API 获取数据?

Flutter:如何在加载页面之前从 Api 获取数据 [关闭]

Flutter:如何从 api 获取数据并在 PaginatedDataTable 中绑定

无法从 Flutter 中的 Open Weather API 获取数据

Flutter 使用 BloC 模式从 API 结果中获取列表元素