Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Api 取回信物邮递员飞_Api_Flutter_Dart_Postman_Bearer Token - Fatal编程技术网

Api 取回信物邮递员飞

Api 取回信物邮递员飞,api,flutter,dart,postman,bearer-token,Api,Flutter,Dart,Postman,Bearer Token,我在我的Flatter项目上创建了一个简单的登录功能,只需输入一封电子邮件和一个密码即可。 现在我想添加postman的令牌承载功能,这样即使应用程序已经关闭,用户仍然可以登录。 我想问的是,如何将令牌承载值放入共享首选项函数中 这是我的登录码 login() async { final response = await http.post( "https://api.batulima.com//v1_ships/login_app", body: {"em

我在我的Flatter项目上创建了一个简单的登录功能,只需输入一封电子邮件和一个密码即可。 现在我想添加postman的令牌承载功能,这样即使应用程序已经关闭,用户仍然可以登录。 我想问的是,如何将令牌承载值放入共享首选项函数中

这是我的登录码

login() async {
final response = await http.post(
  "https://api.batulima.com//v1_ships/login_app",
  body: {"email": email, "password": password},
);
final data = jsonDecode(response.body);
String status = data['status'];
String message = data['message'];
if (status == "success") {
  Navigator.of(context).pushReplacement(PageRouteBuilder(
      pageBuilder: (_, __, ___) => new bottomNavBar(),
      transitionDuration: Duration(milliseconds: 600),
      transitionsBuilder:
          (_, Animation<double> animation, __, Widget child) {
        return Opacity(
          opacity: animation.value,
          child: child,
        );
      }));
  print(message);
} else {
  print(message);
 }
}
我应该添加什么才能从apikey检索值

下面是我在main.dart中创建的getpref。如果为null,则从初始屏幕开始,直到登录页面。如果apikey已经保存,它将进入底部导航栏页面

Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
SharedPreferences prefs = await SharedPreferences.getInstance();
var apikey = prefs.getString('apikey');
print(apikey);
runApp(MaterialApp(
  debugShowCheckedModeBanner: false,
  home: apikey == null ? splash() : bottomNavBar()));
}
Future main()异步{
WidgetsFlutterBinding.ensureInitialized();
SharedReferences prefs=等待SharedReferences.getInstance();
var apikey=prefs.getString('apikey');
打印(apikey);
runApp(材料应用程序)(
debugShowCheckedModeBanner:false,
home:apikey==null?splash():bottomNavBar());
}

您可以复制粘贴运行下面的完整代码
要在JSON中检索apikey的值,您可以执行
data['data']['apikey']

代码片段

String apiKey = data['data']['apikey'];
print("apiKey $apiKey");

SharedPreferences prefs = await SharedPreferences.getInstance();   
await prefs.setString('apiKey', apiKey);

String getedApiKey = await prefs.getString('apiKey');
print(getedApiKey);
输出

I/flutter (22942): apiKey ak5neGVDd3h4M0lVeVF2b2hXWjg3OEZMYUlvcWExTXRqQ21xSmJGWQ==
I/flutter (22942): ak5neGVDd3h4M0lVeVF2b2hXWjg3OEZMYUlvcWExTXRqQ21xSmJGWQ==
I/flutter (22942): login successfully 
完整代码

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  login() async {
    /*final response = await http.post(
      "https://api.batulima.com//v1_ships/login_app",
      body: {"email": email, "password": password},
    );*/
    String jsonString = '''
    {
"status": "success",
"data": {
    "apikey": "ak5neGVDd3h4M0lVeVF2b2hXWjg3OEZMYUlvcWExTXRqQ21xSmJGWQ==",
    "id_user": 49,
    "id_role": "8",
    "name_role": "Ship Owner",
    "email": "afriansyahm86@gmail.com",
    "phone": "082258785595",
    "saldo": "0",
    "photo": "https://batulimee.com/foto_user/avatar.png"
},
"message": "login successfully "
}
    ''';
    final response = http.Response(jsonString, 200);

    final data = jsonDecode(response.body);
    String status = data['status'];
    String message = data['message'];
    String apiKey = data['data']['apikey'];
    print("apiKey $apiKey");

    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('apiKey', apiKey);

    String getedApiKey = await prefs.getString('apiKey');
    print(getedApiKey);

    if (status == "success") {
      /* Navigator.of(context).pushReplacement(PageRouteBuilder(
          pageBuilder: (_, __, ___) => new bottomNavBar(),
          transitionDuration: Duration(milliseconds: 600),
          transitionsBuilder:
              (_, Animation<double> animation, __, Widget child) {
            return Opacity(
              opacity: animation.value,
              child: child,
            );
          }));*/
      print(message);
    } else {
      print(message);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: login,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}
导入'dart:convert';
导入“package:shared_preferences/shared_preferences.dart”;
进口“包装:颤振/材料.省道”;
将“package:http/http.dart”导入为http;
void main(){
runApp(MyApp());
}
类MyApp扩展了无状态小部件{
@凌驾
小部件构建(构建上下文){
返回材料PP(
标题:“颤振演示”,
主题:主题数据(
主样本:颜色。蓝色,
视觉密度:视觉密度。自适应平台密度,
),
主页:MyHomePage(标题:“颤振演示主页”),
);
}
}
类MyHomePage扩展StatefulWidget{
MyHomePage({Key,this.title}):超级(Key:Key);
最后的字符串标题;
@凌驾
_MyHomePageState createState()=>\u MyHomePageState();
}
类_MyHomePageState扩展状态{
int _计数器=0;
login()异步{
/*最终响应=等待http.post(
"https://api.batulima.com//v1_ships/login_app",
正文:{“email”:email,“password”:password},
);*/
字符串jsonString='''
{
“状态”:“成功”,
“数据”:{
“apikey”:“AK5NEGVDD3H4M0LVEVF2B2 HXWJG3OEZMYULVCWEXTXRQQ21XSMJGWQ=”,
“id_用户”:49,
“id_角色”:“8”,
“名称\角色”:“船东”,
“电子邮件”:afriansyahm86@gmail.com",
“电话”:“08225878595”,
“saldo”:“0”,
“照片”:https://batulimee.com/foto_user/avatar.png"
},
“消息”:“登录成功”
}
''';
最终响应=http.response(jsonString,200);
最终数据=jsonDecode(response.body);
字符串状态=数据['status'];
字符串消息=数据['message'];
字符串apiKey=data['data']['apiKey'];
打印(“apiKey$apiKey”);
SharedReferences prefs=等待SharedReferences.getInstance();
等待参数设置字符串('apiKey',apiKey);
String getedApiKey=await prefs.getString('apiKey');
打印(getedApiKey);
如果(状态=“成功”){
/*导航器.of(上下文).pushReplacement(PageRouteBuilder(
页面生成器:(,,,,_)=>新底部导航栏(),
转换持续时间:持续时间(毫秒:600),
转换生成器:
(uu,动画,uu,小部件子项){
返回不透明度(
不透明度:animation.value,
孩子:孩子,
);
}));*/
打印(信息);
}否则{
打印(信息);
}
}
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(
标题:文本(widget.title),
),
正文:中(
子:列(
mainAxisAlignment:mainAxisAlignment.center,
儿童:[
正文(
“您已经按了这么多次按钮:”,
),
正文(
“$”计数器“,
风格:Theme.of(context).textTheme.headline4,
),
],
),
),
浮动操作按钮:浮动操作按钮(
onPressed:login,
工具提示:“增量”,
子:图标(Icons.add),
),
);
}
}

您可以复制粘贴运行下面的完整代码
要在JSON中检索apikey的值,您可以执行
data['data']['apikey']

代码片段

String apiKey = data['data']['apikey'];
print("apiKey $apiKey");

SharedPreferences prefs = await SharedPreferences.getInstance();   
await prefs.setString('apiKey', apiKey);

String getedApiKey = await prefs.getString('apiKey');
print(getedApiKey);
输出

I/flutter (22942): apiKey ak5neGVDd3h4M0lVeVF2b2hXWjg3OEZMYUlvcWExTXRqQ21xSmJGWQ==
I/flutter (22942): ak5neGVDd3h4M0lVeVF2b2hXWjg3OEZMYUlvcWExTXRqQ21xSmJGWQ==
I/flutter (22942): login successfully 
完整代码

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  login() async {
    /*final response = await http.post(
      "https://api.batulima.com//v1_ships/login_app",
      body: {"email": email, "password": password},
    );*/
    String jsonString = '''
    {
"status": "success",
"data": {
    "apikey": "ak5neGVDd3h4M0lVeVF2b2hXWjg3OEZMYUlvcWExTXRqQ21xSmJGWQ==",
    "id_user": 49,
    "id_role": "8",
    "name_role": "Ship Owner",
    "email": "afriansyahm86@gmail.com",
    "phone": "082258785595",
    "saldo": "0",
    "photo": "https://batulimee.com/foto_user/avatar.png"
},
"message": "login successfully "
}
    ''';
    final response = http.Response(jsonString, 200);

    final data = jsonDecode(response.body);
    String status = data['status'];
    String message = data['message'];
    String apiKey = data['data']['apikey'];
    print("apiKey $apiKey");

    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('apiKey', apiKey);

    String getedApiKey = await prefs.getString('apiKey');
    print(getedApiKey);

    if (status == "success") {
      /* Navigator.of(context).pushReplacement(PageRouteBuilder(
          pageBuilder: (_, __, ___) => new bottomNavBar(),
          transitionDuration: Duration(milliseconds: 600),
          transitionsBuilder:
              (_, Animation<double> animation, __, Widget child) {
            return Opacity(
              opacity: animation.value,
              child: child,
            );
          }));*/
      print(message);
    } else {
      print(message);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: login,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}
导入'dart:convert';
导入“package:shared_preferences/shared_preferences.dart”;
进口“包装:颤振/材料.省道”;
将“package:http/http.dart”导入为http;
void main(){
runApp(MyApp());
}
类MyApp扩展了无状态小部件{
@凌驾
小部件构建(构建上下文){
返回材料PP(
标题:“颤振演示”,
主题:主题数据(
主样本:颜色。蓝色,
视觉密度:视觉密度。自适应平台密度,
),
主页:MyHomePage(标题:“颤振演示主页”),
);
}
}
类MyHomePage扩展StatefulWidget{
MyHomePage({Key,this.title}):超级(Key:Key);
最后的字符串标题;
@凌驾
_MyHomePageState createState()=>\u MyHomePageState();
}
类_MyHomePageState扩展状态{
int _计数器=0;
login()异步{
/*最终响应=等待http.post(
"https://api.batulima.com//v1_ships/login_app",
正文:{“email”:email,“password”:password},
);*/
字符串jsonString='''
{
“状态”:“成功”,
“数据”:{
“apikey”:“AK5NEGVDD3H4M0LVEVF2B2 HXWJG3OEZMYULVCWEXTXRQQ21XSMJGWQ=”,
“id_用户”:49,
“id_角色”:“8”,
“名称\角色”:“船东”,
“电子邮件”:afriansyahm86@gmail.com",
“电话”:“08225878595”,
“saldo”:“0”,
“照片”:https://batulimee.com/foto_user/avatar.png"
},
“消息”:“登录成功”
}
''';
最终响应=http.response(jsonString,200);
最终数据=jsonDecode(response.body);
字符串状态=数据['status'];
字符串消息=数据['message'];
字符串apiKey=data['data']['apiKey'];
打印(“apiKey$apiKey”);
SharedReferences prefs=等待