我想實作具有功能的登錄頁面,并且登錄應該由帶有 post 方法的 rest Api 驗證,并且應該使用 Retrofit 完成集成,登錄后用戶應該登陸主頁,也應該使用 SharedPrefrences 來存盤所需的憑據。這樣當用戶登錄時,登錄螢屏就不會一次又一次地顯示。如何開始實施這一切?
我試過了,但不明白接下來會發生什么:
登錄頁面:
import 'package:flutter/material.dart';
import 'package:task1/HomePage.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
// This widget is the root of your application.
bool _isLoading = false;
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Trails',
theme: ThemeData(
primarySwatch: Colors.green,
),
home: MainPage()
);
}
}
class MainPage extends StatefulWidget {
@override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Trails"),
),
body: SingleChildScrollView(
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 60.0),
child: Center(
child: Container(
child: Image.asset('assets/logo.png')),
),
),
Padding(
//padding: const EdgeInsets.only(left:15.0,right:
15.0,top:0,bottom: 0),
padding: EdgeInsets.symmetric(horizontal: 15),
child: TextFormField(
maxLines: 1,
decoration: InputDecoration(
labelText: 'Username',
hintText: 'Enter your username'),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your username';
}
return null;
},
),
),
Padding(
padding: const EdgeInsets.only(
left: 15.0, right: 15.0, top: 15, bottom: 0),
//padding: EdgeInsets.symmetric(horizontal: 15),
child: TextFormField(
obscureText: true,
maxLines: 1,
decoration: InputDecoration(
labelText: 'Password', hintText: 'Enter secure password'),
validator: (value) {
if (value!.trim().isEmpty) {
return 'Enter the password';
} else
return null;
},
),
),
Align(
alignment: Alignment.bottomRight,
child: FlatButton(
onPressed: () {
},
child: Text(
'Forgot Password',
style: TextStyle(fontSize: 12),
),
),
),
Container(
height: 40,
width: 125,
decoration: BoxDecoration(
color: Color.fromRGBO(76, 175, 80, 1), borderRadius: BorderRadius.circular(20)),
child:ElevatedButton(
onPressed: () {
// Validate returns true if the form is valid, or false otherwise.
if (_formKey.currentState!.validate()) {
Navigator.push( context, MaterialPageRoute(builder: (context) => HomePage()),
);
}
},
child: const Text('Login'),
),
),
],
),
),
),
);
}
}
APIClient.dart:
import 'package:retrofit/http.dart';
import 'package:dio/dio.dart';
import 'APIClient.dart';
@RestApi(baseUrl: "https://api.*****.****/authentication")
abstract class APIClient {
factory APIClient(Dio dio) = _APIClient;
@POST("/login")
@FormUrlEncoded()
Future<LoginResponse> loginPage(@Field("username")username,@Field("password")password);
}
回購類:
import 'APIClient.dart';
import 'package:dio/dio.dart';
**class RepoClass{
late APIClient mClient;
RepoClass(){
mClient= APIClient(Dio());
}
loginPage() async {
var username = "black_coder";
var password = "123456";
var loginModel = await mClient.loginPage(username,password);
//You can use your login model data as per your requirements.
}**
但在 APIClient.dar 上出現錯誤說
The name '_APIClient' isn't a type and can't be used in a redirected constructor.
Try redirecting to a different constructor.
uj5u.com熱心網友回復:
創建 SharedPreferences 實體并將令牌保存為您的首選密鑰
void signIn() async {
var data = {'mobile': mobile, 'password': password};
var res = await Network().signIn(data, '/login');
var body = json.decode(res.body);
if (res.statusCode == 200) {
SharedPreferences localStorage = await SharedPreferences.getInstance();
localStorage.setString('token', json.encode(body['data'] ['token']));
localStorage.setString('data', json.encode(body['data']));
Navigator.pushReplacement(context, new MaterialPageRoute(builder: (context) => HomePage()),
);
} else if (res.statusCode != 200) {
// mobileError = "These credentials do not match our records.";
}
}
uj5u.com熱心網友回復:
您可以在自述檔案和示例部分閱讀有關改造(網路處理程式)和 shared_preference(用于保存登錄狀態)的更多資訊
改造:https ://pub.dev/packages/retrofit
shared_preference:https ://pub.dev/packages/shared_preferences
改造示例:演示 Github 鏈接: https ://github.com/HienNguyen102/flutter_retrofit
APIClient.dart
import 'package:retrofit/retrofit.dart';
import 'package:dio/dio.dart';
part 'APIClient.g.dart';
@RestApi(baseUrl: "https://example.com")
abstract class APIClient {
factory APIClient(Dio dio) = _APIClient;
@POST("/login")
@FormUrlEncoded()
Future<String> loginPage(@Field("email")emailId,@Field("password")password);
}
不要忘記添加這些
dependencies:
retrofit: ^3.0.1
dio: ^4.0.4
json_annotation: ^4.4.0
json_serializable: ^6.1.4
dev_dependencies:
retrofit_generator: ^4.0.1
build_runner: ^2.1.7
并運行
flutter pub run build_runner build
所以你可以得到這個
part 'APIClient.g.dart';
下一節課
RepoClass.dart
class RepoClass{
APIClient mClient;
RepoClass(){
mClient= APIClient(Dio());
}
loginPage() async {
var email = "[email protected]";
var password = "123456";
var loginModel = await mClient.loginPage(email,password);
//You can use your login model data as per your requirements.
}
}
共享偏好示例
//Save string data
prefs.setString('email', "[email protected]");
prefs.setString('password', "123456");
//Get string data
string email = prefs.getString('email');
string password = prefs.getString('password');
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/420703.html
標籤:
