面试题答案
一键面试- 配置路由:
- 在
MaterialApp
中配置routes
,定义首页和详情页的路由。例如:
MaterialApp( routes: { '/': (context) => HomePage(), '/detail': (context) => DetailPage(), }, );
- 在
- 处理深度链接:
- 使用
WidgetsFlutterBinding.ensureInitialized()
初始化Flutter绑定。 - 调用
Uri
类解析深度链接的Uri
。例如:
final uri = Uri.parse('your - deep - link - url?productId = 123');
- 提取参数,这里是商品ID:
final productId = uri.queryParameters['productId'];
- 使用
- 导航到详情页:
- 在首页处理深度链接逻辑时,使用
Navigator.pushNamed
方法导航到详情页并传递参数。例如:
Navigator.pushNamed(context, '/detail', arguments: productId);
- 在首页处理深度链接逻辑时,使用
- 在详情页接收参数:
- 在
DetailPage
的initState
方法或构建方法中接收参数。例如:
class DetailPage extends StatefulWidget { @override _DetailPageState createState() => _DetailPageState(); } class _DetailPageState extends State<DetailPage> { String productId; @override void initState() { super.initState(); final args = ModalRoute.of(context).settings.arguments as String; productId = args; } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('商品详情')), body: Center( child: Text('商品ID: $productId'), ), ); } }
- 在
- Android和iOS平台配置:
- Android:在
AndroidManifest.xml
文件中配置深度链接的意图过滤器。例如:
<activity android:name=".MainActivity"> <intent - filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="your - scheme" android:host="your - host" /> </intent - filter> </activity>
- iOS:在
Info.plist
文件中配置深度链接。例如:
<key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLName</key> <string>your - bundle - url - name</string> <key>CFBundleURLSchemes</key> <array> <string>your - scheme</string> </array> </dict> </array>
- Android:在