Flutter火车票务预订插件trainman_booking_sdk的使用

Flutter火车票务预订插件trainman_booking_sdk的使用

Flutter集成步骤

  1. 在依赖项中添加flutter插件

    • 使用命令:
      flutter pub add trainman_booking_sdk
      
    • 手动添加:
      dependencies:
        flutter:
          sdk: flutter
        trainman_booking_sdk: ^0.1.7
      
  2. 实现 TmBookingInterface 接口

    • 该接口包含以下函数:
      void openLoginPage(String message, String source);
      void backPressed(BuildContext context);
      void refreshToken(String? pastAuthToken, String source);
      
  3. 创建 InitiateTmBookingSdk 对象

    import 'package:trainman_booking_sdk/trainman_booking_sdk.dart';
    
    class SampleCode extends StatelessWidget { 
      const SampleCode({Key? key}) : super(key: key);
    
      [@override](/user/override)
      Widget build(BuildContext context) {  
          // 初始化trainman booking sdk
          return const InitiateTmBookingSdk(
            tmBookingInterface: TrainBookingInterface(), // 实现了TmBookingInterface的类
            source: Source.home, // 来源标识
            data: const {
              "os_type": "Android",
              "access_token": "null"
            },
            appId: "1.1.1.1",
            appVersion: "demo",
            isLogsEnabled: true,
            userAgent: "TestAgent",
          ); 
      } 
    }
    

    这将自动调用Trainman Booking SDK。访问令牌是可选参数。如果在成功认证后需要刷新访问令牌,可以使用 updateAccessToken(String? accessToken, String? refreshToken) 方法。

  4. 点击 Continue without login 按钮

  5. 对于Android设备,确保已添加Internet权限

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android">
      <uses-permission android:name="android.permission.INTERNET" />
      <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    </manifest>
    

注意:目前我们已经调用了一个中间页面来登录测试用户进行测试。客户端用户登录集成后,这一步将被跳过。

完整示例代码

import 'package:example/trainman_booking_interface.dart';
import 'package:flutter/material.dart';
import 'package:trainman_booking_sdk/trainman_booking_sdk.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    // 设置环境变量
    Constants.setEnv(Env.adl);
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: InitiateTmBookingSdk(
        tmBookingInterface: TrainBookingInterface(),
        source: Source.home,
        data: const {
          "os_type": "Android",
          "access_token": "null"
        },
        appId: "1.1.1.1",
        appVersion: "demo",
        isLogsEnabled: true,
        userAgent: "TestAgent",
      ),
    );
  }
}

更多关于Flutter火车票务预订插件trainman_booking_sdk的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter火车票务预订插件trainman_booking_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


trainman_booking_sdk 是一个用于火车票务预订的 Flutter 插件,它允许开发者在其 Flutter 应用中集成火车票预订功能。以下是如何使用 trainman_booking_sdk 的基本步骤:

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 trainman_booking_sdk 的依赖。

dependencies:
  flutter:
    sdk: flutter
  trainman_booking_sdk: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来获取依赖。

2. 初始化 SDK

在你的 Flutter 应用启动时,需要初始化 trainman_booking_sdk。通常,你可以在 main.dart 文件中进行初始化。

import 'package:flutter/material.dart';
import 'package:trainman_booking_sdk/trainman_booking_sdk.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await TrainmanBookingSdk.initialize(
    apiKey: 'YOUR_API_KEY',  // 替换为你的API密钥
    environment: Environment.sandbox,  // 使用沙盒环境进行测试
  );
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Trainman Booking Demo',
      home: HomeScreen(),
    );
  }
}

3. 使用 SDK 进行火车票预订

你可以在应用的任何地方使用 TrainmanBookingSdk 提供的功能。例如,搜索火车、查看座位可用性、预订车票等。

import 'package:flutter/material.dart';
import 'package:trainman_booking_sdk/trainman_booking_sdk.dart';

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Trainman Booking'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            try {
              // 搜索火车
              final trains = await TrainmanBookingSdk.searchTrains(
                fromStation: 'NDLS',  // 起点站代码
                toStation: 'BCT',     // 终点站代码
                date: DateTime.now(), // 出发日期
              );

              // 显示搜索结果
              showDialog(
                context: context,
                builder: (context) => AlertDialog(
                  title: Text('Trains Found'),
                  content: Text('${trains.length} trains found.'),
                ),
              );
            } catch (e) {
              // 处理错误
              showDialog(
                context: context,
                builder: (context) => AlertDialog(
                  title: Text('Error'),
                  content: Text(e.toString()),
                ),
              );
            }
          },
          child: Text('Search Trains'),
        ),
      ),
    );
  }
}

4. 处理预订流程

你可以使用 TrainmanBookingSdk 提供的其他方法来处理预订流程,例如选择座位、输入乘客信息、确认预订等。

// 示例:确认预订
final bookingResult = await TrainmanBookingSdk.confirmBooking(
  trainId: '12345',
  passengers: [
    Passenger(
      name: 'John Doe',
      age: 30,
      gender: Gender.male,
    ),
  ],
);

if (bookingResult.success) {
  // 预订成功
  showDialog(
    context: context,
    builder: (context) => AlertDialog(
      title: Text('Booking Successful'),
      content: Text('Your PNR: ${bookingResult.pnr}'),
    ),
  );
} else {
  // 预订失败
  showDialog(
    context: context,
    builder: (context) => AlertDialog(
      title: Text('Booking Failed'),
      content: Text(bookingResult.errorMessage),
    ),
  );
}

5. 处理支付

trainman_booking_sdk 可能还提供了支付功能,你可以使用它来处理支付流程。

// 示例:处理支付
final paymentResult = await TrainmanBookingSdk.processPayment(
  bookingId: '67890',
  paymentMethod: PaymentMethod.creditCard,
);

if (paymentResult.success) {
  // 支付成功
  showDialog(
    context: context,
    builder: (context) => AlertDialog(
      title: Text('Payment Successful'),
      content: Text('Your booking is confirmed.'),
    ),
  );
} else {
  // 支付失败
  showDialog(
    context: context,
    builder: (context) => AlertDialog(
      title: Text('Payment Failed'),
      content: Text(paymentResult.errorMessage),
    ),
  );
}

6. 错误处理

在使用 SDK 时,务必处理可能出现的错误。你可以使用 try-catch 块来捕获异常并进行相应的处理。

try {
  final trains = await TrainmanBookingSdk.searchTrains(
    fromStation: 'NDLS',
    toStation: 'BCT',
    date: DateTime.now(),
  );
} catch (e) {
  // 处理错误
  showDialog(
    context: context,
    builder: (context) => AlertDialog(
      title: Text('Error'),
      content: Text(e.toString()),
    ),
  );
}
回到顶部